0

我正在尝试加入 3 个表 - e, wp,l

位置为 l :name | id | workplace_id

作为 wp 的工作场所:name | id

雇员为 e :name | id | location_id | 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
4

2 回答 2

-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

那是你要找的吗?

于 2012-06-08T22:54:00.233 回答
-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;
于 2012-06-08T22:56:49.023 回答