我有一张可以发给不同部门的客户表。每个客户端都可以分配到多个部门,每个部门都有多个客户端。 因此我有一个:
client table which includes (clientID,client info...)
departments table which includes a (departmentID,department info...)
connecting table (assign_ID,client_ID,departmentID).
在寻找分配到2个部门之一的客户时,sql语句很简单:
select * from clients join connectingtable on... join departments on... where departmentID=1 or departmentID=2
但是当我需要一个AND语句时我该怎么办?我需要同时分配到2个部门的客户。我不能用AND替换OR,因为这将要求每行我将插入2个ID,这是不可能的。我该怎么解决这个问题?
答案 0 :(得分:0)
一种方法是使用两个EXISTS
子句:
WHERE EXISTS(SELECT client_ID
FROM connecting c
WHERE departmentID = 1
and c.client_ID = connecting.client_id) // or use alias from outer query instead of "concecting"
AND EXISTS(SELECT client_ID
FROM connecting c
WHERE departmentID = 2
and c.client_ID = connecting.client_id)
答案 1 :(得分:0)
在部门上使用左连接两次,并检查第一次和第二次连接是否有结果。
SELECT * FROM Clients WHERE CliendID IN
(SELECT CliendID
FROM clients join connectingtable on...
LEFT JOIN departments DEP1 on...
LEFT JOIN departments DEP2 on...
WHERE DEP1.departmentID IS NOT NULL AND DEP2.DepartmentID IS NOT NULL)
答案 2 :(得分:0)
我建议的查询与@Dejan提出的查询非常类似,但避免使用IN(...)形式:
SELECT *
FROM Clients C
INNER JOIN (SELECT C1.ClientID
FROM Clients C1
INNER JOIN connecting CT1 ON CT1.ClientID = C1.ClientID
INNER JOIN departments D1 ON D1.DepartmentID = CT1.DepartmentID
AND D1.departmentID = 1) DP1 ON DP1.ClientID = C.ClientID
INNER JOIN (SELECT C2.ClientID
FROM Clients C2
INNER JOIN connecting CT2 ON CT2.ClientID = C2.ClientID
INNER JOIN departments D2 ON D2.DepartmentID = CT2.DepartmentID
AND D2.departmentID = 2) DP2 ON DP2.ClientID = C.ClientID
希望这是你正在寻找的。 p>
答案 3 :(得分:-1)
select * from clients a
where (select count(*) from connectingtable b
where a.clientID = b.clientID) > 1