我有两个“一对多”关系的表。
TblProjects
ProjectID
.........
TblCustomers
ProjectID
Number
.........
如何获得所有 ProjectIDs
满足此条件的所有Customers
Number % 100 = 0
答案 0 :(得分:2)
一般解决方案是使用queue.take()
反向条件(NOT EXISTS
而不是<>
):
=
这是SQLFiddle。
或者,特定于此用例,您可以使用更简洁的查询:
SELECT DISTINCT p.ProjectID
FROM TblProjects p INNER JOIN TblCustomers ct
ON ct.ProjectID = p.ProjectID
WHERE NOT EXISTS
(SELECT 1
FROM TblCustomers c
WHERE c.ProjectID = p.ProjectID AND (Number % 100) <> 0)
这是SQLFiddle。
P.S。如果仅需要SELECT p.ProjectID
FROM TblProjects p INNER JOIN TblCustomers ct
ON ct.ProjectID = p.ProjectID
GROUP BY p.ProjectID
HAVING MAX(ct.Number % 100) = 0
,则根本不需要加入任何内容,只需直接使用ProjectID
即可。
答案 1 :(得分:0)
您可以使用内连接
Select * from tblProjects pro
inner join tblCustomers cst on pro.projectID = cst.ProjectID
and cst.Number % 100 = 0
它将为您提供您所要求的内容
答案 2 :(得分:0)
你可以使用CTE来获取可读的查询:
;with
not_all_at_100 as
( select distinct c.ProjectID
FROM TblCustomers c
WHERE (c.Number % 100) != 0
),
all_project_customers as
( select ProjectID
FROM TblCustomers
)
select distinct p.ProjectID
from TblProjects p
where p.ProjectID in ( select ProjectID from all_project_customers )
and p.ProjectID not in ( select ProjectID from not_all_at_100 )