2012-06-08 97 views
0

之間,我試圖加入3個表 - ewpl加入3個MySQL表W /查詢在

位置爲L:name | id | workplace_id

工作場所爲wp:name | id

員工e:name | id | location_id | coordinator

我想: 如果一個WORKPLACE有一個協調員在任何位置 (協調= 1),得到工作場所的所有地點

這似乎並不奏效 - 它返回工作場所有協調= 1的所有位置,但我需要的所有位置如果任何工作場所地點的協調員= 1,則爲工作場所。

select distinct w.* 
from workplaces as w, 
    (select distinct l.* 
    from locations as l, employees as e 
    where e.location_id = l.id and e.coordinator = 1) as tmp 
where tmp.workplace_id = w.id 

回答

-1
select distinct l.* 
from locations as l, workplaces as w, 
    (select distinct l.* 
    from locations as l, employees as e 
    where e.location_id = l.id and e.coordinator = 1) as tmp 
where l.workplace_id = w.id 
and tmp.workplace_id = w.id 

這就是你想要的?

-1

首先,子查詢是一個非常糟糕的主意,對於進行連接,您應該使用以下任意一種:內連接,左連接或右連接。那麼你可以有這樣的事情:

SELECT l.* FROM locations as l 
INNER JOIN workplaces w ON l.workplace_id = w.id 
INNER JOIN employees e ON l.id = e.location_id 
WHERE e.coordinator = 1; 
+0

......這正是Andypandy已經擁有的東西。 – zessx