如何使用where子句对列和ORDER BY列进行随机播放

时间:2016-02-03 17:51:52

标签: mysql

MySQL表共有50行(记录)。有两列。 Column1具有10个记录的值。 Column2具有40个记录的值。在结果中,Column1必须先到Column2。 Column1必须与where子句一起混洗,例如Column1 =' 1'。然后来自Column2的15条记录(如果需要,可以在这里使用where子句)必须是ORDER BY DESC。然后必须对Column2的剩余记录进行洗牌。怎么做?。请帮忙。我需要查询。

Select * 
from mytable 
where column1='1' rand(), column2 
ORDER BY DESC limit 15, column2 rand();

1 个答案:

答案 0 :(得分:0)

使用UNION

SELECT * FROM 
    (SELECT *
    FROM mytable
    WHERE column1 = '1'
    ORDER BY RAND()) AS t1
UNION ALL
    (SELECT *
    FROM mytable
    WHERE column2 != ''
    ORDER BY column2 DESC
    LIMIT 15)
UNION ALL
    (SELECT *
    FROM mytable
    WHERE column2 != ''
    AND column2 NOT IN (
        SELECT column2
        FROM mytable
        WHERE column2 != ''
        ORDER BY column2 DESC
        LIMIT 15)
    ORDER BY RAND())