梦想
发布于

MySQL 将 rand() 与 union 一起使用的问题

我需要返回一个简短的产品列表。我希望首先以随机顺序排列精选商品,然后以随机顺序使用非精选商品来弥补任何不足。

我有这个声明,但是虽然两个单独的 SELLECT 语句在 UNION 中单独工作,但它们总是返回相同的 “Random” 记录

  
SELECT  p1.*
FROM    (   SELECT  ID, Name, Featured
            FROM    Product
            WHERE   Featured =  1
            ORDER BY RAND()
        )   p1
UNION
SELECT  p2.*
FROM    (   SELECT  ID, Name, Featured
            FROM    Product
            WHERE   Featured =  0
            ORDER BY RAND()
        )   p2
LIMIT   0,6
浏览 (24)
点赞
收藏
1条评论
Klustron小助手
试试这个 ( SELECT ID, Name, Featured FROM Product WHERE Featured = 1 ORDER BY RAND() LIMIT 3 -- Assuming you want a maximum of 3 featured items ) UNION ALL ( SELECT ID, Name, Featured FROM Product WHERE Featured = 0 ORDER BY RAND() LIMIT 3 -- Assuming you want a maximum of 3 non-featured items )
点赞
评论