UNION
構文:
<SQL文1> union <SQL文2>;
サンプル:
select name from kittens where id between 1 and 2 union select name from kittens where id between 2 and 3;
データ:
mysql> select * from kittens; +----+-------+-----------+ | id | name | friend_id | +----+-------+-----------+ | 1 | mii | 3 | | 2 | tora | 3 | | 3 | shiro | 1 | | 4 | kuro | NULL | +----+-------+-----------+ 4 rows in set (0.01 sec)
サンプルの実行結果:
mysql> select name from kittens where id between 1 and 2 union select name from kittens where id between 2 and 3; +-------+ | name | +-------+ | mii | | tora | | shiro | +-------+ 3 rows in set (0.00 sec)
実行結果の比較を行うため、UNIONするSQLは同じカラムを返すSQL同士でなければなりません。カラムの数が違ったりする場合、エラーです。
mysql> select name from kittens where id = 1 union select * from kittens where id = 2; ERROR 1222 (21000): The used SELECT statements have a different number of columns