MySQL Count函数将两列的结果相乘(应分别返回每列的计数)

时间:2018-08-17 04:47:00

标签: mysql sql database join count

我有一个用户表,一个任务表和一个提醒表。我想返回每个用户的任务数和提醒数。当我只计算一个或另一个(无论是提醒还是任务)时,我就可以使用它,但是当我在一个查询中将两者都计算时,由于某种原因它们会彼此相乘。

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       |
+-------------------------------------------+

3 个答案:

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

答案 1 :(得分:1)

您将得到交叉连接,每项任务的每条提示。

尝试

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

答案 2 :(得分:0)

尝试以下查询

SELECT ID,电子邮件,name,(从提醒r中选择COUNT(id)r.id = u.id)作为提醒, (从任务t中选择COUNT(id)t在哪里t.id = u.id)作为用户u用户的任务