MySQL fetching a key value pair which are in two different columns

感情迁移 提交于 2019-12-25 04:13:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!