MySQL - 基于Key / Value表中的2个键加入表

时间:2010-09-30 21:28:51

标签: sql mysql query-optimization

我有一个设置表,可以显示为: object_id(int) key(varchar) 价值(文字)

我正在尝试抓住具有等于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'

虽然我没有测试过最后一个声明,但我确信这样的事情可行。此查询将每小时在可能数十万条记录上执行,因此我希望保持优化 - 有更好的方法吗?

1 个答案:

答案 0 :(得分: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'