开发者

How to use MYSQL LIMIT per person

开发者 https://www.devze.com 2023-04-03 13:33 出处:网络
So I have a scenario where there are 1-8 people that i need to query up to 3 things they \"liked\" per person.I have the query开发者_StackOverflow中文版 set up as

So I have a scenario where there are 1-8 people that i need to query up to 3 things they "liked" per person. I have the query开发者_StackOverflow中文版 set up as

SELECT liked FROM likeTable WHERE uid IN (uid1,uid2,uid3,uid4) LIMIT 12

but obviously this can potentially stop when i have 12 "likes" for uid1, leaving the rest at 0. I read a possible solution as using UNION ALL for example...

(SELECT liked FROM likeTable WHERE uid = uid1 LIMIT 3)
UNION ALL
(SELECT liked FROM likeTable WHERE uid = uid2 LIMIT 3)
UNION ALL
(SELECT liked FROM likeTable WHERE uid = uid3 LIMIT 3)
UNION ALL
(SELECT liked FROM likeTable WHERE uid = uid4 LIMIT 3)

And i would be able to achieve this by making the sql query string in php with a forloop, but is this an efficient way of querying my data?

note: I don't really care about the order in which the "liked" is retrieved, although it would be nice if i could add an ORDER BY likeID DESC, which is my autoincrementing column

Thanks!


For small number (not hundreds, I would say) of categories (users), just use the union solution.

And would I be able to achieve this by making the sql query string in php with a forloop, but is this an efficient way of querying my data?

Definitelly yes! Unless you query hundreds of users in one go. For 1-8 people, it is just perfect solution!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号