[英]MySQL COUNT() not returning total number it is counting each rows separately
[英]MySQL Count function multiplying results of two columns (Should be returning count of each column separately)
我有一個用戶表,一個任務表和一個提醒表。 我想返回任務計數和每個用戶的提醒計數。 當我只計算一個或另一個(提醒或任務)時,我可以讓它工作但當我在一個查詢中計算它們時,由於某種原因它們相互成倍增加。
SQLFiddle: http ://www.sqlfiddle.com/#!9 / f0d6696 / 1/0
這是我目前的查詢:
SELECT
users.name,
COUNT(reminders.id),
COUNT(tasks.id)
FROM users
LEFT JOIN reminders on users.id = reminders.id
LEFT JOIN tasks on users.id = tasks.id
GROUP BY users.id
這是我的用戶表的樣子:
+---------------------------------------+
| ID | Name | Email |
+---------------------------------------+
| 1 | John Smith | jsmith@email.com |
| 2 | Mark Twain | mtwain@books.com |
| 3 | Elon Musk | space-dude@email.com|
+---------------------------------------+
這是我的任務表的樣子:
+------------------------------------------------+
| ID | Title | Text | Status |
+------------------------------------------------+
| 1 | Dishes | Kitchen = nasty | incomplete|
| 1 | Library | drop off books | complete |
| 3 | Gym | get swole dude | incomplete|
+------------------------------------------------+
這是我的提醒表的樣子:
+------------------------------------+
| ID | Title | Text |
+------------------------------------+
| 1 | Dishes | Kitchen = nasty |
| 2 | Library | drop off books |
| 1 | Gym | get swole dude |
+------------------------------------+
我希望從以上查詢中獲得以下結果:
+-------------------------------------------+
| Name | Tasks | Reminders |
+-------------------------------------------+
| John Smith | 2 | 2 |
| Mark Twain | 1 | 0 |
| Elon Musk | 0 | 1 |
+-------------------------------------------+
我實際上得到以下內容:
+-------------------------------------------+
| Name | Tasks | Reminders |
+-------------------------------------------+
| John Smith | 4 | 4 | <---2 tasks x 2 reminders?
| Mark Twain | 1 | 0 |
| Elon Musk | 0 | 1 |
+-------------------------------------------+
請嘗試下面的內部計數: http : //www.sqlfiddle.com/#!9 / f0d6696 / 12
SELECT
users.name,
count(distinct reminders.title) as rtitle,
count(distinct tasks.title) as ttitle
FROM users
LEFT JOIN reminders on users.id = reminders.id
LEFT JOIN tasks on users.id = tasks.id
group by users.name
您正在獲得交叉加入,每個任務的每個提醒。
嘗試
select
users.name,
remindercount,
taskcount
FROM users
LEFT JOIN (select id, count(*) as remindercount from reminders group by id) reminders on users.id = reminders.id
LEFT JOIN (select id, count(*) as taskcount from tasks group by id) tasks on users.id = tasks.id
嘗試使用以下查詢
SELECT id,email, name
,(SELECT COUNT(id)FROM reminders r WHERE r.id = u.id)AS提醒,(SELECT COUNT(id)FROM tasks t WHERE t.id = u.id)AS task FROM users ü
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.