I have a very simple table and here is the values.
id photo_name user_id created_at
----------------------------------------------
144 Photo1 1 2014-05-01 09:30:15
143 Photo2 2 2014-05-01 10:30:15
142 Photo3 1 2014-05-01 11:30:15
141 Photo4 3 2014-05-01 12:30:15
140 Photo5 1 2014-05-01 13:30:15
139 Photo6 2 2014-05-01 14:30:15
139 Photo6 2 2014-05-01 14:30:15
Expected result
I want to limit 2 photos per user_id
id photo_name user_id created_at
----------------------------------------------
144 Photo1 1 2014-05-01 11:30:15
142 Photo3 1 2014-05-01 12:30:15
143 Photo2 2 2014-05-01 13:30:15
139 Photo6 2 2014-05-01 14:30:15
141 Photo4 3 2014-05-01 14:30:15
I've tried several ways but couldn't get the desired result. Thanks for help in advance!
The easiest way in MySQL is to use variables:
select id, photo_name, user_id, created_at
from (select p.*,
@rn := if(@uid = user_id, @rn + 1, 1) as rn,
@uid := user_id
from photos p cross join
(select @uid := -1, @rn := 0) var
order by user_id
) p
where rn <= 2;
There is another way using standard SQL:
select p.*
from photos p
where 2 >= (select count(*)
from photos p2
where p2.user_id = p.user_id and
p2.id <= p.id
);
What the subquery query does is count the number of photos by a given user. The p2.user_id = p.user_id
restricts the query to just the user. The p2.id <= p.id
puts in an ordering. So the lowest id
for a user has only one match (itself) and the count is 1
. The next has two matches -- the lowest and itself -- so the value is 2. And so on.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.