如何排除MySQL查询中的匹配记录?

时间:2016-05-05 00:41:43

标签: php mysql sql join

我正在尝试根据以下表格获取等待服务和空闲代理的客户列表:

Customers Table
|Customers_ID||Customer Name|
|1           ||John         |
|2           ||Sam          |
|3           ||Kuji         |

Agents Table
|AGENT_ID||AGENT Name|
|99      ||Kelly     |
|98      ||Raji      |
|97      ||Mertle    |

Service Table (Customers being served by Agents)
|QUE_ID||AGENT Name||Customer|
|1001  ||Kelly     ||Kuji    |
|1002  ||Raji      ||Sam     |

SELECT Customer.custname 

FROM Customer LEFT JOIN Service ON ( Customer.custname = Service.custname)

UNION 

SELECT Agent.agentname

FROM Agent RIGHT JOIN Service ON ( Agent.agentname = Service.agentname)

WHERE 
(Agent.agentname = service.agentname) IS NULL 

GROUP BY Customer.custname";

这将返回customer表中的所有值,而不是没有代理的客户。如何排除已匹配的记录?

3 个答案:

答案 0 :(得分:0)

您可以使用NOT EXISTS检查尚未在Service表中的代理商和客户:

SELECT custname
FROM Customer c
WHERE NOT EXISTS(
    SELECT 1
    FROM Service s
    WHERE s.custname = c.custname
)

UNION ALL

SELECT agentname
FROM Agent a
WHERE NOT EXISTS(
    SELECT 1
    FROM Service s
    WHERE s.agentname = a.agentname
)

答案 1 :(得分:0)

看起来你正在尝试进行完全外连接。虽然MySQL没有install_failed_insufficient_storage关键字,但您可以通过两个左连接的并集来模拟它。下面的查询中的左连接给出了空闲客户和代理的数量。关键部分是FULL OUTER JOIN条件,它将匹配尚未分配的客户或代理。

WHERE ... IS NULL

答案 2 :(得分:0)

LEFT或RIGHT JOIN将确保返回所有没有或具有NULL值的列的记录(在最终表中)。

您可以按照以下方式使用NOT EXISTS(这将减少记录数量,而不是所有记录数量):

SELECT custname
FROM Customer
WHERE NOT EXISTS (SELECT custname
FROM Service
WHERE Customer.custname = Service.custname)

UNION ALL

SELECT agentname
FROM Agent
WHERE NOT EXISTS(SELECT agentname 
FROM Service s 
WHERE s.agentname = a.agentname)