Halo我正在尝试查询从一个表中选择记录,只有在第二个表'deal_unpluged'中找不到匹配的记录时才说'deal_asking'。这就是我所做的(下面)使用LEFT JOIN选择记录然后在PHP端过滤记录。 我正在寻找一个解决这个问题的Mysql查询方式,请帮助..
提前感谢...
SELECT DA.das_id, DU.das_id_fk
FROM deal_asking DA
LEFT JOIN deal_unpluged DU ON DA.das_id= DU.das_id_fk
WHERE department='8'
ORDER BY das_id ASC LIMIT 10 OFFSET 0
答案 0 :(得分:4)
只需将其添加到您的WHERE
子句:
AND DU.das_id_fk IS NULL
说我有以下两个表:
+-------------------------+ +-------------------------+ | Person | | Pet | +----------+--------------+ +-------------------------+ | PersonID | INT(11) | | PetID | INT(11) | | Name | VARCHAR(255) | | PersonID | INT(11) | +----------+--------------+ | Name | VARCHAR(255) | +----------+--------------+
我的表包含以下数据:
+------------------------+ +---------------------------+ | Person | | Pet | +----------+-------------+ +-------+----------+--------+ | PersonID | Name | | PetID | PersonID | Name | +----------+-------------+ +-------+----------+--------+ | 1 | Sean | | 5 | 1 | Lucy | | 2 | Javier | | 6 | 1 | Cooper | | 3 | tradebel123 | | 7 | 2 | Fluffy | +----------+-------------+ +-------+----------+--------+
现在,如果我想要所有Person
的列表:
SELECT pr.PersonID, pr.Name
FROM
Person pr
如果我想要一张有宠物的Person
名单(包括他们的宠物名字):
SELECT pr.PersonID, pr.Name, pt.Name AS PetName
FROM
Person pr
INNER JOIN Pet pt ON pr.PersonID = pt.PersonID
如果我想要一张没有宠物的Person
列表:
SELECT pr.PersonID, pr.`Name`
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
WHERE
pt.`PetID` IS NULL
如果我想要所有Person
及其宠物的清单(即使他们没有宠物):
SELECT
pr.PersonID,
pr.Name,
COALESCE(pt.Name, '<No Pet>') AS PetName
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
如果我想要一份Person
的清单以及他们有多少宠物的数量:
SELECT pr.PersonID, pr.Name, COUNT(pt.PetID) AS NumPets
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
GROUP BY
pr.PersonID, pr.Name
与上述相同,但不显示带有0只宠物的Person
:
SELECT pr.PersonID, pr.Name, COUNT(pt.PetID) AS NumPets
FROM
Person pr
LEFT JOIN Pet pt ON pr.PersonID = pt.PersonID
GROUP BY
pr.PersonID, pr.Name
HAVING COUNT(pt.PetID) > 0