问题
Table1 : Has 3 columns say id, key & value.
+----+-----+-------+
| ID | KEY | VALUE |
+----+-----+-------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 2 | 2 |
| 5 | 3 | 1 |
| 6 | 3 | 2 |
| 7 | 4 | 1 |
| 8 | 4 | 2 |
| 9 | 5 | 1 |
| 10 | 5 | 2 |
+----+-----+-------+
This table key and value both can be repeated but the combination of both is unique.
If I want to query for multiple rows based on the key value pair and NOT on id. How can I do that ?
NOTE: I know I can do this
SELECT * from Table1
WHERE (key=1 AND value=2) OR
(key=1 AND value=1) OR
(key=5 AND value=1);
I was hope to something much better and concise as I have approximately 40K key value pairs which I need to query for.
回答1:
There is no other proper way than what you are already doing. You should rather compare on the unique column, which in you case is ID. yes you can shorten it using a IN operator to compare row constructors saying
SELECT * from Table1
WHERE (`key`, `value`) IN ((1,2),(1,1),(5,1));
See MySQL Documentation for more information on the same.
来源:https://stackoverflow.com/questions/32769907/mysql-fetching-a-key-value-pair-which-are-in-two-different-columns