将3个sql表与/之间的查询连接起来

时间:2012-06-08 22:29:36

标签: mysql join left-join

我正在尝试加入3个表格 - ewpl

位置为l:name | id | workplace_id

工作场所为wp:name | id

员工e:name | id | location_id | coordinator

我想: 如果WORKPLACE在任何位置有COORDINATOR(协调员= 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

2 个答案:

答案 0 :(得分:-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 :(得分:-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;