使用条件从2个表中检索数据

时间:2011-04-01 18:14:10

标签: mysql sql join

我有2张桌子

+---------------------+
|       T_EQUIPMENT   |
+----+--------+---+---+
| ID | NAME   |APPROVED|
+----+--------+---+---+
| 01 | foo1   |  0    |
+----+--------+---+---+
| 02 | foo2   |  1    |
+----+--------+---+---+
| 03 | foo3   |  1    |
+----+--------+---+---+
| 04 | foo4   |  1    |
+----+--------+---+---+

+---------------------------+
|       T_HAS_EQUIPMENT     |
+----+------------+----+----+
| ID_CENTER | ID_EQUIP      |
+----+------------+----+----+
|     12    |      2        |
+----+------------+----+----+
|     3     |      3        | 
+----+------------+----+----+
|     3     |      2        |
+----+------------+----+----+
|     5     |      3        |
+----+-----------+----+----+
|     6     |      2        |
+----+------------+----+----+

我想获得id,已批准设备的名称(APPROVED = 1)以及此特定中心是否有此设备

例如id_center = 3我想要这个

    +---------------------+
    |       RESULT        |
    +----+--------+---+---+
    | ID | NAME   |  HAS  |
    +----+--------+---+---+
    | 02 | foo2   |  1    |
    +----+--------+---+---+
    | 03 | foo3   |  1    |
    +----+--------+---+---+
    | 04 | foo4   |  0    |
    +----+--------+---+---+

所以,我检索所有设备,我知道一个中心是否有这个设备。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

使用:

   SELECT e.id, 
          e.name,
          CASE 
            WHEN he.id_center IS NOT NULL THEN 1 
            ELSE 0
          END AS has
     FROM T_EQUIPMENT e
LEFT JOIN T_HAS_EQUIPMENT he ON he.id_equip = e.id
                            AND he.id_center = 3
    WHERE e.approved = 1
 ORDER BY e.id

使用OUTER(LEFT,RIGHT)连接对表格放置过滤条件可以大大改变输出。在此示例中,在创建JOIN之前过滤id_center。如果它在WHERE子句中,则之后将应用过滤。