如何选择wach user_id
的行等于每个user_id
的选择计数?
我的示例表:
mp3_id | user_id
--------------------
120 | 840
123 | 840
126 | 840
128 | 455
130 | 840
131 | 840
132 | 840
135 | 840
144 | 840
158 | 840
159 | 455
161 | 455
169 | 455
180 | 840
181 | 455
184 | 455
186 | 455
189 | 455
我的简单查询:
select mp3_id where user_id IN (840,455) limit 8
retuen:
mp3_id | user_id
--------------------
120 | 840
123 | 840
126 | 840
128 | 455
130 | 840
131 | 840
132 | 840
135 | 840
但我想选择这个:
mp3_id | user_id
--------------------
120 | 840
123 | 840
126 | 840
130 | 840
128 | 455
159 | 455
161 | 455
169 | 455
我希望每个user_id
返回相等的行数。如何?感谢
答案 0 :(得分:3)
您可以使用UNION执行此操作:
select mp3_id where user_id = 840 limit 4
union all
select mp3_id where user_id = 455 limit 4
答案 1 :(得分:2)
尝试此查询:
select
yt.mp3_id,
e.user_id
from
(
select distinct user_id from your_table
) e
join your_table yt on true
where yt.mp3_id in (select tt.mp3_id from your_table tt where tt.user_id = e.user_id order by tt.mp3_id limit 4)
和相同的查询但有条件
select
yt.mp3_id,
e.user_id
from
(
select distinct user_id from your_table where user_id in (840,455)
) e
join your_table yt on true
where yt.mp3_id in (select tt.mp3_id from your_table tt where tt.user_id = e.user_id order by tt.mp3_id limit 4)
答案 2 :(得分:1)
SELECT x.*
FROM my_table x
JOIN my_table y
ON y.user_id = x.user_id
AND y.mp3_id <= x.mp3_id
GROUP
BY x.mp3_id HAVING COUNT(*) <= 4
ORDER
BY user_id DESC
, mp3_id;
或更快
SELECT mp3_id, user_id FROM
(
SELECT x.*, CASE WHEN @prev = user_id THEN @i:=@i+1 ELSE @i:=1 END i, @prev:=user_id FROM my_table x, (SELECT @prev:=null,@i:=1) vars ORDER BY user_id DESC, mp3_id
) a
WHERE i<=4;