2010-09-30 66 views
0

我有設置的表,其可以被示出爲: 的object_id(INT) 鍵(VARCHAR) 值(文本)的MySQL - 加入根據2個密鑰的表從一個鍵/值表

我試圖抓住具有等於2項的鍵的object_id。

SELECT `object_id` FROM `settings` WHERE `key` = 'A' AND `key` = 'B' 

我知道這是行不通的,我能想到這樣做的唯一的辦法就是加入它本身:

SELECT a.`object_id` FROM `settings` AS a LEFT JOIN `settings` AS b ON (a.`object_id` = b.`object_id`) WHERE a.`key` = 'A' and b.`key` = 'B' 

雖然我沒有測試過的最後一條語句,我肯定這樣的事情可以工作。這個查詢將每小時執行數十萬條記錄,所以我想保持它的優化 - 有沒有更好的方法來做到這一點?

回答

2

哦,你想:

SELECT `object_id` 
    FROM `settings` 
    WHERE (`key` = 'A' AND `value`='foo') 
     OR (`key`= 'B' AND `value`='bar') 
GROUP BY `object_id` 
    HAVING COUNT(*) = 2 

用途:

SELECT `object_id` 
    FROM `settings` 
    WHERE `key` IN ('A', 'B') 
GROUP BY `object_id` 
    HAVING COUNT(DISTINCT `key`) = 2 

或者:

SELECT x.`object_id` 
    FROM `settings` AS x 
    JOIN `settings` AS y ON y.`object_id` = x.`object_id` 
WHERE x.`key` = 'A' 
    AND y.`key` = 'B' 
+0

感謝 - 正是我一直在尋找的 - 這將是可以指定值來匹配那些鍵?如果'key' ='a'AND'value' ='b'? – 2010-09-30 21:33:45

+0

@Kerry:對不起?那些是不同的列和值,不需要JOIN或GROUP BY/HAVING – 2010-09-30 21:36:32

+0

是的 - 我的頭腦現在有點混亂,畫幾個空白,謝謝 - 你的解決方案是完美的(不知道第一個是可能) – 2010-09-30 21:39:02