选择列,其中3行包含单独的值 - 自我加入?

时间:2018-02-02 15:51:08

标签: mysql

寻找执行select语句的最佳方法。我认为SELF JOIN是最好的方法,但我很难将它组合在一起。任何帮助或指导将不胜感激。

我有一个项目元表:

+----------+----------+-------+
| item_num | field_id | meta  |
+----------+----------+-------+
|      800 |      508 | red   |
|      800 |      507 | shirt |
|      800 |      504 | 2     |
|      700 |      508 | red   |
|      700 |      507 | shirt |
|      700 |      504 | 3     |
|      500 |      508 | red   |
|      500 |      507 | shirt |
|      500 |      504 | 5     |
+----------+----------+-------+

从表WHERE:

中选择item_num
  1. field_id = 508 AND meta = red
  2. field_id = 507 AND meta = shirt
  3. field_id = 504 AND meta = 2
  4. 我最初的陈述想法:

    SELECT   a.item_num
    FROM     Table a
      JOIN   Table b
      JOIN   Table c
          ON a.item_num = b.item_num = c.item_num
         AND a.field_id = 508
         AND a.meta = red
         AND b.field_id = 507
         AND b.meta = shirt
         AND c.field_id = 504
         AND c.meta = 2
    GROUP BY a.item_num
    LIMIT 1
    

1 个答案:

答案 0 :(得分:2)

使用分组更容易

 SELECT item_num
 FROM YourTable
 GROUP BY item_num
 HAVING COUNT(CASE WHEN field_id=508 AND meta='red' THEN 1 END) > 0
    AND COUNT(CASE WHEN field_id=507 AND meta='shirt' THEN 1 END) > 0
    AND COUNT(CASE WHEN field_id=504 AND meta='2' THEN 1 END) > 0

也可以写成

 HAVING COUNT(CASE WHEN field_id=508 AND meta='red'   THEN 1 
                   WHEN field_id=507 AND meta='shirt' THEN 1 
                   WHEN field_id=504 AND meta='2'     THEN 1 
              END) = 3