如何使用MYSQL LIMIT每人

发布于 2024-12-03 14:23:09 字数 669 浏览 2 评论 0原文

所以我有一个场景,有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流星番茄 2024-12-10 14:23:09

对于少量(不是数百,我想说)类别(用户),只需使用联合解决方案。

我是否能够通过使用 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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文