2
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,所以我想问一下是否有一种方法可以算作上述结果?

4

2 回答 2

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

要全面了解联接,请访问以下链接:

于 2013-01-28T09:25:22.050 回答
0

采用LEFT JOIN

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

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

关键字返回左表 (staffinfo) 中的LEFT JOIN所有行,即使右表 (ticket) 中没有匹配项。

于 2013-01-28T09:45:45.460 回答