SQL LEFT JOIN两个表而不使用GROUP BY

时间:2013-11-17 09:13:26

标签: sql

我有3张桌子:

组织:

---------------------------
|  ID   |  Name | Owner   |     
---------------------------

project_clients:

----------------------------------
|  ID   |  identification | Type  |     
-----------------------------------

project_organizations:

---------------------------------
|  ID   |  project_id | orgid   |     
---------------------------------

我想拉下项目680下的所有组织或项目680下类型为'组织'的所有客户。我可以使用下面的代码实现这一点但是有没有其他方法可以在不使用GROUP BY的情况下获得相同的结果?

SELECT a.* FROM organization a 
LEFT join project_organizations b on a.id = b.orgid 
LEFT JOIN project_clients c on  c.identification = a.id 
where b.projectid = 680 OR (c.project_id = 680 AND c.type='organization') 
GROUP BY a.id

1 个答案:

答案 0 :(得分:0)

你正在寻找这个吗?

SELECT DISTINCT a.id 
FROM organization a 
LEFT join project_organizations b on a.id = b.orgid 
LEFT JOIN project_clients c on  c.identification = a.id where b.projectid = 680 OR (c.project_id = 680 AND c.type='organization') 

我认为你也可以通过像这样的查询以完全不同的方式实现你的结果

select * 
from organization a 
where id in (select ordid from project_organizations b where projectid=680) 
or id in (select c.id from project_clients C where c.project_id=680 and c.type='organization')