MySQL 按随机顺序但显示不同的前 5 个结果?
好的,我有 3 个 MySQL
表 公司 优惠
我希望某人单击“类别”页面,从而以随机顺序向他们显示每家公司的优惠,这样就不会优先考虑任何人。一家公司可以有 1 到 10 个报价,并且可以有任意数量的报价链接到一个类别。
这一切都工作正常,但我希望显示来自独特公司的前 5 名(或更多,无论最简单的)报价。下面的其他内容可以按任何顺序排列,只要它们不重复前 5 名中已经显示的内容即可。
不确定解决此问题的最佳方法,因为这有点超出了我的能力 - 是否会进行 2 个查询并左加入它们,排除第二个查询中第一个查询中的报价 ID?
非常感谢任何帮助!
Ok I've got 3 MySQL tables
Categories
Companies
Offers
I want someone to click onto a Category page, whereby they are shown offers from each company in a random order, so that no-one is given preference. A company can have anywhere between 1 and 10 offers and there can be any number of offers linked to a category.
This is all working fine but I want the top 5 (or more, whatever is easiest) offers to be displayed to be from unique companies. The others underneath can be in any order as long as they don't repeat those already showin in the top 5.
Not sure of the best way to go about this as it's a bit outside my ability - would it be to do 2 queries and left join them, excluding the offer ids from the first query in the second one?
Any help much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一定有一种更有效的方法来做到这一点,但我的大脑今天还没有达到 100% 的状态。怎么样 -
更新:将 EXISTS 添加到内部公司 SELECT 中,
然后从主 SELECT 语句中排除这 5 个 Offer_ids 。
There must be a more efficient way of doing this but my brain is not at 100% today. How about -
UPDATE: Added EXISTS to the inner companies SELECT
then exclude these 5 offer_ids from you main SELECT statement.
未经测试,但类似的东西应该可以工作。我们可以查看您当前的查询吗?
Untested but something like this should work. Can we see your current query?
我使用了 nnichols 建议的内容,但进行了调整(由于某种原因,最初的查询需要 3.5 秒才能运行),所以我使用了这个:
它只需要
0.0088
来运行。然后,我存储了正在使用的优惠 ID,并使用 nnichols 的NOT IN
进行第二次查询,现在效果很好,再次感谢大家的帮助:)
I used what nnichols suggested but tweaked (the initial query was taking 3.5 seconds to run for me for some reason) so I used this:
Which is only taking
0.0088
to run. I then stored the offer id's being used and used theNOT IN
from nnichols for the second query, it works great nowThanks again for everyone's help :)