Mysql交叉点中的单列多重过滤器

时间:2010-04-21 20:00:42

标签: mysql filter intersection

这是一张表

CarID| Attribute    | Value
1   | Color     | Red
2   | Color     | Blue 
3   | Color     | Red 
1   | Type      | Coupe 
2   | Type      | Hatch Back 
3   | Type      | Coupe
3   | Make      | Honda
2   | Make      | Toyota
1   | Make      | Ford

现在我想运行一个过滤器,如Select * From Cars WHERE(Attribute = Color AND Value = Red)AND(Attribute = Make AND Value = Honda)....并希望将CarID设为3! / p>

这是2个查询的交集的简单情况,但我不知道如何在单个查询中完成它。

任何有用的帮助。

3 个答案:

答案 0 :(得分:3)

select
      carid,
      count(*) matchedItems
   from
      YourTable
   where
        ( Attribute = 'Color' and Value = 'Red' )
     OR ( Attribute = 'Make' and Value = 'Honda' )
   group by 
      carid 
   having
      matchedItems = 2;

您可能需要更改必须...

 having count(*) = 2

答案 1 :(得分:1)

最直接的解决方案是使用子查询为每个属性模拟一个单独的表(尽管它可能不是最有效的):

SELECT Colors.CarID FROM
    ( SELECT CarID, Value FROM Cars WHERE Attribute = 'Color' ) Colors,
    ( SELECT CarID, Value FROM Cars WHERE Attribute = 'Make' ) Makes
    WHERE Colors.CarID = Makes.CarID AND Colors.Value = 'Red' AND
        Makes.Value = 'Honda';

答案 2 :(得分:0)

以下是查询的另一种变体

SELECT carid
FROM AnotherUnknownTableName t INNER JOIN  
     AnotherUnknownTableName t2 ON t.carid = t2.carid AND 
                                   t.Attribute = 'Color' AND 
                                   t2.Attribute = 'Make'
WHERE 
     t.Value = 'Red' AND t2.Value = 'Honda'

索引(carid,属性)会产生奇迹。