从同一用户中选择仅最多3行 - MySQL

时间:2009-10-02 14:06:01

标签: sql mysql

假设有两个表:

使用列表“照片”:

id,
title,
path,
user_id

用表格列出“用户”:

id
username

我想要做的是从“照片”表中选择30张照片,但条件是在获取的结果集中最多有3张来自同一用户的照片。到目前为止,我有这个问题:

SELECT p.*, u.username FROM photos AS p 
INNER JOIN users AS u ON u.id = p.user_id 
ORDER BY p.id DESC LIMIT 30;

如何创建WHERE子句以实现最大值。在获取的结果集中来自同一用户的3行?

编辑:我正在使用MySQL 5.1.33

4 个答案:

答案 0 :(得分:4)

SELECT p.*, u.username 
FROM photos AS p 
INNER JOIN users AS u ON u.id = p.user_id 
WHERE p.id in (
 SELECT id  
 FROM photos p
 WHERE user_id  = p.user_id 
 LIMIT 3
)
ORDER BY p.id DESC LIMIT 30;

答案 1 :(得分:3)

好的,这是一种“聪明”的方法:

SELECT u.username, p1.* FROM photos AS p1
 INNER JOIN users AS u ON u.id=p1.user_id
 LEFT OUTER JOIN photos AS p2 ON p2.user_id=p1.user_id and p2.id <= p1.id
 GROUP BY p1.id
 HAVING COUNT(p2.id) <= 3
 LIMIT 30;

话虽如此,厌倦了“聪明”的代码。它让你在短期内感觉良好,但维护可能很痛苦。

答案 2 :(得分:2)

我会看this technique。你的where子句是     在哪里row_number&lt; 3

然后     限制30

答案 3 :(得分:1)

从T-SQL手工翻译,在MySQL上未经测试。

SELECT p.*, u.username
FROM photos AS p
INNER JOIN users AS u ON u.id = p.user_id
WHERE p.id IN (
 SELECT p1.id
 FROM photos p1
 JOIN photos p2
 ON p1.user_id = IFNULL( p2.user_id, p1.user_id )
 AND p1.id <= IFNULL( p2.id, p1.id )
 GROUP BY p1.id
 HAVING COUNT(*) < 4
)
LIMIT 30