MySQL :如何使用复合主键上的 "IN" 过滤查询
MySQL : How to filter query using "IN" on Composite Primary Key
我在 MySQL 中有一个 table 这样的主键是这样的复合键:
+--------------+----+------------------------------+
| fk_something | id | label |
+--------------+----+------------------------------+
| 1 | 1 | First record of something 1 |
| 2 | 1 | First record of something 2 |
| 2 | 2 | Second record of something 2 |
| 1 | 2 | Second record of something 1 |
| 2 | 3 | Third record of something 2 |
+--------------+----+------------------------------+
但现在我有一个棘手的查询要做,我想使用“IN”过滤器检索例如 2-1 和 1-2 记录...我该怎么做?
我试过类似的东西:
SELECT * FROM my_table WHERE id IN (1, 2) AND fk_something IN (2, 1)
但它也给了我 1-1 和 2-2 的记录...
您可以利用很少使用的 SQL 功能 row value expressions:
SELECT * FROM myTable
WHERE (id, fk_something) IN (
(1, 2),
(2, 1),
(2, 3)
)
我在 MySQL 中有一个 table 这样的主键是这样的复合键:
+--------------+----+------------------------------+
| fk_something | id | label |
+--------------+----+------------------------------+
| 1 | 1 | First record of something 1 |
| 2 | 1 | First record of something 2 |
| 2 | 2 | Second record of something 2 |
| 1 | 2 | Second record of something 1 |
| 2 | 3 | Third record of something 2 |
+--------------+----+------------------------------+
但现在我有一个棘手的查询要做,我想使用“IN”过滤器检索例如 2-1 和 1-2 记录...我该怎么做?
我试过类似的东西:
SELECT * FROM my_table WHERE id IN (1, 2) AND fk_something IN (2, 1)
但它也给了我 1-1 和 2-2 的记录...
您可以利用很少使用的 SQL 功能 row value expressions:
SELECT * FROM myTable
WHERE (id, fk_something) IN (
(1, 2),
(2, 1),
(2, 3)
)