代码之家  ›  专栏  ›  技术社区  ›  Kerry Jones

mysql-从key/value表中加入基于2个键的表

  •  0
  • Kerry Jones  · 技术社区  · 14 年前

    我有一个设置表,可以显示为: 对象ID(int) 密钥(VARCHAR) 价值(文本)

    我正在尝试获取键等于2项的对象\u 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 回复  |  直到 14 年前
        1
  •  2
  •   OMG Ponies    14 年前

    哦,你想要:

      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'