在SQL中对m / n个连接表计数值

时间:2014-03-05 18:38:51

标签: mysql sql

我有四张桌子,想知道某个名字有多少个位置和下载。 nameslocations通过names_locations

连接

以下是我的表格:

表“names

ID | name
=========
 1 | foo
 2 | bar
 3 | zoo
 4 | luu

表“locations

ID | location
=============
 1 | Hamburg
 2 | New York
 3 | Singapore
 4 | Tokio

表“names_locations

ID | location_id | name_id
==========================
 1 | 1           | 1
 2 | 1           | 2
 3 | 2           | 2
 4 | 3           | 3
 5 | 1           | 2

表“downloads

ID | name_id | timestamp
=========================
 1 | 1       | 1394041682
 2 | 4       | 1394041356
 3 | 1       | 1394041573
 4 | 3       | 1394041981
 5 | 1       | 1394041683

结果应该是:

ID | name | locations | downloads
=================================
 1 | foo  | 1         | 3
 2 | bar  | 3         | 0
 3 | zoo  | 1         | 1
 4 | luu  | 0         | 1

这是我的尝试(没有下载列):

SELECT names.*, 
       Count(names_locations.location_id) AS location 
FROM   names 
       LEFT JOIN names_locations 
              ON names.ID = names_locations.name_id 
GROUP  BY names.ID 

3 个答案:

答案 0 :(得分:2)

我认为这样可行。

SELECT n.id,
       n.name,
       COUNT(DISTINCT l.id) AS locations,
       COUNT(DISTINCT d.id) AS downloads
FROM names n LEFT JOIN names_location nl
  ON n.id = nl.name_id
LEFT JOIN downloads dl
  ON n.id = dl.name_id
LEFT JOIN locations l
  ON l.id = nl.location_id
GROUP BY n.id, n.name

答案 1 :(得分:1)

所有这些似乎都有效。这是另一个。

SELECT 
  a.ID,
  a.name,
  COUNT(c.location) AS locations,
  COUNT(d.timestamp) AS downloads 
FROM names AS a
  LEFT JOIN names_locations AS b on a.ID=b.name_id
  LEFT JOIN locations AS c ON b.location_id=c.ID
  LEFT JOIN downloads AS d ON a.ID=d.name_id
GROUP BY a.name

答案 2 :(得分:1)

SELECT
  t.id,t.n AS name,
  count(location_id) AS locations,
  t.downloads
FROM names_location 
RIGHT JOIN 
 (SELECT 
    names.id AS id,
    names.name AS n, 
    count(timestamp) AS downloads 
  FROM names
    LEFT JOIN downloads ON names.id = downloads.name_id
    GROUP BY id) AS t 
ON t.id = names_location.name_id
GROUP BY t.id

输出:

+------+------+-----------+-----------+
| id   | name | locations | downloads |
+------+------+-----------+-----------+
|    1 | foo  |         1 |         3 |
|    2 | bar  |         3 |         0 |
|    3 | zoo  |         1 |         1 |
|    4 | luu  |         0 |         1 |
+------+------+-----------+-----------+
4 rows in set (0.00 sec)