如何从表X中选择与表Y共享最少关系的行?

时间:2014-10-08 22:38:42

标签: php mysql sql

假设我们有以下两个表

TABLE: PEOPLE
+----+------+
| id | name |
+----+------+
| 1  | john |
+----+------+
| 2  | mike |
+----+------+
| 3  | derp |
+----+------+

TABLE: Images
+----+-----------+----------+
| id | person_id | image    |
+----+-----------+----------+
| 1  | 3         | img1.jpg |
+----+-----------+----------+
| 2  | 3         | img2.jpg |
+----+-----------+----------+
| 3  | 2         | img3.jpg |
+----+-----------+----------+

我需要一个查询,从people表中选择所有人,并通过图像表中图像最少的人对ASC进行排序

因此返回行的顺序为

John
Mike
Derp

1 个答案:

答案 0 :(得分:4)

对images表进行外连接,然后计算每个用户的非空图像ID数。

SELECT p.id,
       p.name,
       COUNT(i.id) AS image_count
FROM PEOPLE p
LEFT OUTER JOIN Images i
    ON p.id = i.person_id
GROUP BY p.id,
         p.name
ORDER BY COUNT(i.id);

SQLFiddle。)