如果在其他表中找不到匹配记录,如何从一个表中选择记录

时间:2014-01-31 13:45:36

标签: php mysql sql

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 

1 个答案:

答案 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