技術と日常。

日々の気が付いたこと・気になったことを残しておきます。

[SQL]WHERE ~ IN句を複数条件(タプル)にて指定する方法は?

WHERE ~ IN句を複数条件(タプル)にて指定する方法

以下のテーブルを考えます

mysql> CREATE TABLE fruits (
    ->     category_1 int,
    ->     category_2 int,
    ->     fruit varchar(10)
    -> );
Query OK, 0 rows affected (0.06 sec)

mysql> INSERT INTO fruits VALUES
    -> (1, 1, "apple"),
    -> (1, 2, "banana"),
    -> (2, 1, "kiwi"),
    -> (2, 2, "orange");
Query OK, 4 rows affected (0.01 sec)

mysql> SELECT * FROM fruits;
+------------+------------+--------+
| category_1 | category_2 | fruit  |
+------------+------------+--------+
|          1 |          1 | apple  |
|          1 |          2 | banana |
|          2 |          1 | kiwi   |
|          2 |          2 | orange |
+------------+------------+--------+
4 rows in set (0.00 sec)

ここで、(category_1, category_2)(1, 1)(2, 2)のものを取得したいと考えます。

ANDとORを使用しても書けるのですが……、

SELECT fruit FROM fruits
WHERE (category_1 = 1 AND category_2 = 1)
OR (category_1 = 2 AND category_2 = 2);

以下のようにINを使うことで、スマートに書くことが可能です。

SELECT fruit FROM fruits
WHERE (category_1, category_2) IN ((1, 1), (2, 2));

PostgreSQL, DB2に関しては、VALUESが必要のようです

SELECT fruit FROM fruits
WHERE (category_1, category_2) IN (VALUES (1, 1), (2, 2));

参考

mysql - selecting where two columns are in a set - Database Administrators Stack Exchange