我目前正在寫有三個表的MySQL的GroupBy與空/零點導致
一個爲用戶提供客票系統:
users
+----+-----------+----------+
| ID | FirstName | LastName |
+----+-----------+----------+
| 1 | First | User |
| 2 | Second | User |
| 3 | Third | User |
| 4 | Fourth | User |
| 5 | Fifth | User |
+----+-----------+----------+
一個門票:
ticket
+----+---------------+
| ID | TicketSubject |
+----+---------------+
| 1 | Ticket #1 |
| 2 | Ticket #2 |
| 3 | Ticket #3 |
| 4 | Ticket #4 |
+----+---------------+
和一個爲用戶指定動作票(可以每票多於一位用戶):
ticket_assigned
+----+----------+--------+
| ID | TicketID | UserID |
+----+----------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 3 | 5 |
| 5 | 3 | 3 |
+----+----------+--------+
我試圖創建摘要顯示每個用戶,以及他們有多少票分配給他們,例如:
+------------+-------+
| Name | Count |
+------------+-------+
| First | 2 |
| Second | 1 |
| Third | 1 |
| Fourth | 0 |
| Fifth | 1 |
| Unassigned | 2 |
+------------+-------+
注意,最後一項是「未分配」,這是多少記錄在故障單表中,不要出現在ticket_assigned表中(因此,未分配)。另請注意,用戶「Fourth」爲零,因爲該用戶在ticket_assigned表中沒有記錄。
這裏是我使用當前MySQL查詢:
SELECT
CASE
WHEN users.FirstName IS NULL
THEN 'Unassigned'
ELSE users.FirstName
END as 'UserName',
COUNT(*) as 'TicketCount'
FROM tickets
LEFT OUTER JOIN ticket_assigned ON tickets.ticket_id = ticket_assigned.ticket_id
LEFT OUTER JOIN users ON ticket_assigned.user_id = users.user_id
GROUP BY ticket_assigned.user_id
ORDER BY UserName;
問題的是,它沒有顯示,我基本上得到這是任何不中ticket_assigned表功能的用戶:
+------------+-------+
| Name | Count |
+------------+-------+
| First | 2 |
| Second | 1 |
| Third | 1 |
| Fifth | 1 |
| Unassigned | 2 |
+------------+-------+
是否有人能夠協助並告訴我如何修改我的查詢以包含在ticket_assigned表中沒有記錄的用戶?提前致謝!
謝謝你,不顯示未分配? –
@AndrewMilici更新時間。 –