如何使用MYSQL LIMIT每人
所以我有一个场景,有 1-8 个人,我需要查询每人最多 3 件他们“喜欢”的东西。我已将查询设置为,
SELECT liked FROM likeTable WHERE uid IN (uid1,uid2,uid3,uid4) LIMIT 12
但显然,当我对 uid1 有 12 个“喜欢”时,这可能会停止,其余的为 0。我读到了一个可能的解决方案,例如使用 UNION ALL...
(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)
我将能够实现这是通过使用 forloop 在 php 中创建 sql 查询字符串来实现的,但这是查询数据的有效方法吗?
注意:我并不真正关心检索“喜欢”的顺序,尽管如果我可以添加一个 ORDER BY likeID DESC(这是我的自动增量列),那就太好了,
谢谢!
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 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于少量(不是数百,我想说)类别(用户),只需使用联合解决方案。
我是否能够通过使用 forloop 在 php 中创建 sql 查询字符串来实现此目的,但是这是查询数据的有效方法吗?
绝对是的!除非你一次性查询了数百个用户。对于1-8人来说,这只是完美的解决方案!
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!