2011-04-01 45 views
1

從2個表的數據我有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,覈準的設備(認可= 1)的名稱,但也不論這個特定的中心有此設備

例如用於id_center = 3,我想這

+---------------------+ 
    |  RESULT  | 
    +----+--------+---+---+ 
    | ID | NAME | HAS | 
    +----+--------+---+---+ 
    | 02 | foo2 | 1 | 
    +----+--------+---+---+ 
    | 03 | foo3 | 1 | 
    +----+--------+---+---+ 
    | 04 | foo4 | 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 

使用外部(左,右)濾波器的Placement條件對錶加入可以顯着改變它的輸出。在此示例中,id_center在JOIN創建之前被過濾。如果它在WHERE子句中,則將在之後應用過濾。

+0

正是我一直在尋找。謝謝 – poscaman 2011-04-02 07:32:12