MySQL随机排序,但显示前5个结果?

时间:2012-02-16 16:02:55

标签: php mysql random distinct

好的我有3个MySQL表

分类 公司 报价

我希望有人点击“分类”页面,按随机顺序显示每个公司的优惠,以便不给予任何人优先选择。公司可以提供1到10个优惠,并且可以提供与某个类别相关的任意数量的优惠。

这一切都运转良好,但我希望显示来自独特公司的前五名(或更多,最简单的)优惠。下面的其他人可以按任何顺序排列,只要他们不重复已经在前5名中显示的那些。

不确定最好的解决方法,因为它有点超出我的能力 - 它会做2个查询并离开加入它们,不包括第二个查询中第一个查询的商品ID吗?

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:1)

未经测试,但这样的事情应该有效。我们可以看到您当前的查询吗?

SELECT DISTINCT company, and, other, columns 
FROM table
ORDER BY RAND()
LIMIT 5

答案 1 :(得分:1)

必须有一种更有效的方法来做到这一点,但我的大脑今天不是100%。怎么样 -

SELECT
    company_offers.companyid,
    offers.offerid,
    offers.title,
    offers.offer
FROM (
    SELECT
        companies.companyid,
        (
            SELECT offers.offerid
            FROM offers
            WHERE offers.companyid = companies.companyid
            AND categoryid = '%s'
            AND active = 1
            ORDER BY RAND()
            LIMIT 1
        ) AS offerid
    FROM companies
    WHERE EXISTS (SELECT NULL FROM offers WHERE offers.companyid = companies.companyid AND offers.categoryid = '%s' AND offers.active = 1)
    ORDER BY RAND()
    LIMIT 5
) AS company_offers
INNER JOIN offers
    ON company_offers.offerid = offers.offerid

更新:为内部公司SELECT

添加了EXISTS

然后从主SELECT语句中排除这5个offer_id。

SELECT companies.companyid, offers.offerid, offers.title, offers.offer
FROM offers
INNER JOIN companies
    ON companies.companyid = offers.companyid
WHERE offers.categoryid = '%s'
AND offers.active = 1
AND offers.offerid NOT IN (comma separated list of 5 from previous query)
ORDER BY RAND()

答案 2 :(得分:0)

我使用了nnichols建议但调整的内容(由于某些原因,初始查询花了3.5秒为我运行)所以我使用了这个:

SELECT * 
FROM (SELECT offers.companyid, offerid, title, offer 
      FROM companies 
      INNER JOIN offers ON offers.companyid = companies.companyid 
      WHERE offers.categoryid='%s' AND offers.active = '1' 
      ORDER BY RAND()) AS t 
GROUP BY t.companyid 
ORDER BY RAND() 
LIMIT 10

仅运行0.0088。然后我存储了正在使用的商品ID,并使用了来自nnichols的NOT IN进行第二次查询,现在效果很好

再次感谢大家的帮助:)