LoginSignup
6
6

More than 5 years have passed since last update.

みんなの為のMySQLまとめ(3)

Last updated at Posted at 2015-02-07

参考
http://homepage2.nifty.com/sak/w_sak3/doc/sysbrd/mysql_08.htm

■データベース問い合わせ

・リレーショナルデータベース(RDB) では、select 文を用いて、実に様々な
問い合わせが可能である。

・特定のデータを抜き出す指定は次のようにする。
この例では、key1 の先頭が「a」で始まるものだけが問い合わされる。
like は、部分一致を行う。

・複数条件で抽出するには、次のようにする。
この例では、key1 が「a001」と「b002」のものが問い合わされる。
where 句には、and、or を複合条件指定できる。
() で囲まれた条件ほど優先順位が高い。
kobito.1423318774.747088.png

()を付けたとき。

select
key1,
data1,
data2,
data3
from testm
where (key1 = 'a001' or key1 = 'b002') and data1 > 0
order by key1
;

・項目指定に「*」を指定すると、全ての項目が含まれる。

select
*
from testm
where key1 like 'a%'
order by key1
;

・特定の項目を見せたくないときは次のようにする。
この例では、data2 と言う項目がなくなる。

select
key1,
data1,
data3
from testm
order by key1
;

・項目名を異なった項目名に変更する場合は、次のようにする。
この例では、data1 と言う項目名が「abc」と言う項目名に変更されている。

select
key1,
data1 as abc,
data3
from testm
order by key1
;
kobito.1423319456.037350.png
 

・計算項目を作る場合は、次のようにする。
この例では、data1 + data2 の合計が「total」と言う項目名で追加される。
様々な SQL 関数を用いた計算項目が作成できる。

select
key1,
data1 + data2 as total,
data3
from testm
order by key1
;

・文字列の結合項目を作る場合は、次のようにする。
この例では、data1 と data2 の結合文字が「stritem」と言う項目名で追加
される。SQL 関数を用いたフォーマットなども可能である。
MySQL では「||」による結合はできないようである。concat() を使用する。

select
key1,
concat(data1, data2) as stritem,
data3
from testm
order by key1
;
kobito.1423319685.442953.png
 
 
select concat('123', 4);
select concat('123', '4');
select concat('123', cast(4 as char));
select concat('123', convert(4, char));kobito.1423319982.774058.png

・「+」では、次のように数値計算となる。

select '123' + 4;
select '123' + '4';
kobito.1423320161.978382.png 

・strcmp() で文字列の大小比較が次のようにできる。

select strcmp('123', '456');
select strcmp('456', '123');
select strcmp('123', '123');
kobito.1423320316.687005.png

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6