复杂的SQL查询

时间:2009-08-07 08:30:27

标签: sql

我有这些表格:

- Users
    - id
- Photos
    - id
    - user_id
- Classifications
    - id
    - user_id
    - photo_id

我想按照他们拥有的照片+分类总数订购用户。

我写了这个查询:

SELECT users.id, 
COUNT(photos.id) AS n_photo, 
COUNT(classifications.id) AS n_classifications, 
(COUNT(photos.id) + COUNT(classifications.id)) AS n_sum 
FROM users 
LEFT JOIN photos ON (photos.user_id = users.id) 
LEFT JOIN classifications ON (classifications.user_id = users.id) 
GROUP BY users.id 
ORDER BY (COUNT(photos.id) + COUNT(classifications.id)) DESC

问题是这个查询不能像我预期的那样工作并且返回高数字而我在数据库中只有几张照片和分类。它返回如下内容:

id n_photo n_classifications   n_sum
29  19241   19241                   38482
16  16905   16905                   33810
1    431     0                       431
...

4 个答案:

答案 0 :(得分:4)

你遗失了。

  SELECT U.ID, COUNT(DISTINCT P.Id)+COUNT(DISTINCT C.Id) Count
  FROM User U
  LEFT JOIN Photos P ON P.User_Id=U.Id
  LEFT JOIN Classifications C ON C.User_Id=U.Id
  GROUP BY U.Id
  ORDER BY COUNT(DISTINCT P.Id)+COUNT(DISTINCT C.ID)

答案 1 :(得分:1)

我可能会误解你的架构,但不应该这样:

LEFT JOIN classifications ON (classifications.user_id = users.id) 

是这样的:

LEFT JOIN classifications ON (classifications.user_id = users.id) 
                         AND (classifications.photo_id = photos.id)

答案 2 :(得分:0)

SELECT users1.id, users1.n_photo, users2.n_classifications
FROM (
    SELECT users.id, COUNT(photos.id) AS n_photo
    FROM users LEFT OUTER JOIN photos ON photos.user_id = users.id
    GROUP BY users.id
  ) users1
  INNER JOIN (
    SELECT users.id, COUNT(classifications.id) AS n_classifications
    FROM users LEFT OUTER JOIN classifications ON classifications.user_id = users.id
    GROUP BY users.id
  ) users2 ON users1.id = users1.id

答案 3 :(得分:0)

尝试更像这样的东西:

SELECT users.id as n_id,
(SELECT COUNT(photos.id) FROM photos WHERE photos.user_id = n_id) AS n_photos,
(SELECT COUNT(classifications,id) FROM classifications WHERE classifications.user_id = n_id) AS n_classifications,
(n_photos + n_classifications) AS n_sum
FROM users
GROUP BY n_id
ORDER BY n_sum DESC