在一个查询中获取一些随机和一些特定记录?

时间:2011-01-18 20:16:54

标签: sql mysql random

所以我有一个封面流式的图像轮播,填充了像

这样的查询
SELECT foo FROM `imageTable` ORDER BY RAND() LIMIT 0, 12;

我的客户想要添加一组永久图像。由于结果的使用方式,如果我可以将这些记录作为原始查询的一部分,那将非常方便。

我试过

SELECT foo FROM `imageTable` WHERE `id` = 'x' OR `id` = 'y' 
  OR `id` IS NOT NULL ORDER BY RAND() LIMIT 0, 12;

我希望带有id的记录必然会出现在结果集中,但是没有RAND()会对整个集合进行洗牌。

所以我的问题是,任何一个查询是否可以提供x永久记录,然后是y随机记录?

使用Adrian Serafin的答案编辑修改过的查询:

(SELECT * FROM `imageTable` ORDER BY RAND() LIMIT 0, 6)
UNION
(SELECT * FROM `imageTable`  WHERE `id` = 'foo' OR `id` = 'bar' OR `id` = 'baz')

3 个答案:

答案 0 :(得分:4)

您可以在sql中尝试union命令。

select random
  union
select choosed

答案 1 :(得分:1)

你可以试试一个工会......

(SELECT foo FROM imageTable WHERE id not in ( 'x','y') ORDER BY RAND() LIMIT 0, 12; )
UNION
(SELECT foo FROM imageTable WHERE id in ('x','y')
ORDER BY a LIMIT 10;

答案 2 :(得分:1)

将它们联合起来,但阻止X和Y多次显示 您也可以使用IN而不是多个OR语句来更简洁。

SELECT foo FROM (
    SELECT foo FROM `imageTable`
    WHERE id NOT IN ('x','y','z')
    ORDER BY RAND() LIMIT 0, 9    # reduce by 3
) A
UNION ALL
SELECT foo FROM (
    SELECT foo FROM `imageTable`
    WHERE id IN ('x','y','z')
) B
ORDER BY RAND()    # order again so that x,y,z are anywhere in the set