如何连接两个表,保持不符合JOIN条件的行?

时间:2013-01-28 09:24:16

标签: mysql sql select

ticket                      
+----------+--------+
| ticketID | assign |
+----------+--------+
|     1015 | NULL   |
|     1020 | James  |
|     1021 | Nick   |
+----------+--------+

staffinfo
+---------+-------+
| staffID | staff |
+---------+-------+
|       1 | Jane  |
|       2 | James |
|       3 | Nick  |
|       4 | Cole  |
+---------+-------+

SELECT staff,COUNT(*) as count FROM staffinfo,ticket
WHERE ticket.assign = staffinfo.staff
GROUP BY staff

result:
    +-------+-------+
    | staff | count |
    +-------+-------+
    | James |     1 |
    | Nick  |     1 |
    +-------+-------+

工作正常,但事实上我需要像:

+-------+-------+
| staff | count |
+-------+-------+
| James |     1 |
| Nick  |     1 |
| Jane  |     0 |
| Cole  |     0 |
+-------+-------+

COUNT不计算表中不存在的记录,因为我刚刚开始学习SQL,我想问一下是否可以计算上述结果?

2 个答案:

答案 0 :(得分:8)

您应该使用LEFT JOIN

SELECT  a.staff,    COUNT(b.assign) as count 
FROM    staffinfo a
        LEFT JOIN ticket b
            ON b.assign = a.staff
GROUP   BY a.staff

要充分了解联接知识,请访问以下链接:

答案 1 :(得分:0)

使用LEFT JOIN

LEFT JOIN关键字返回左表(table_name1)中的所有行,即使右表(table_name2)中没有匹配项也是如此。

SELECT staffinfo.staff, count(ticket.assign)
FROM staffinfo
LEFT JOIN ticket
ON ticket.assign =staffinfo.staff
GROUP BY staffinfo.staff

LEFT JOIN关键字返回左表(staffinfo)中的所有行,即使右表(票证)中没有匹配项也是如此。