0

我有一个 ID 从 1 到 20 的表,我需要获取 10 行(随机),但是 10 行中有 3 行是预定义的,需要位于结果列表的开头 - 在一个 MySQL 语句中:

这可行,但生产表包含超过 500K 行:

SELECT id 
FROM tableName
WHERE id IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
ORDER BY FIELD(id, 5,6,7) DESC, RAND()
LIMIT 10

我需要这样的东西:

SELECT id 
FROM tableName
WHERE id IN (5,6,7,*)
ORDER BY FIELD(id, 5,6,7) DESC, RAND()
LIMIT 10

...正确的语法是什么?

4

3 回答 3

2

您可以使用这样的语句:

SELECT
  id
  FROM
  (
    SELECT
      id,
      IF(id IN (5,6,7),1,0) AS priority
      FROM tableName
  ) t
  ORDER BY priority DESC, RAND()
  LIMIT 10
于 2013-09-27T14:26:29.977 回答
1

如果允许 UNION ALL,您可以尝试以下操作:

select id from tablename where id in (compulsary_1, compulsary_2, compulsary_3)
  order by id desc
union all
select id from tablename where id not in (compulsary_1, compulsary_2, compulsary_3)
  order by rand() limit 7
于 2013-09-27T14:29:28.687 回答
0

到处玩......我发现了这个并且也有效:

SELECT id
FROM tableName
WHERE id IN (5,6,7) OR id > 0
ORDER BY FIELD(id,5,6,7) DESC, RAND() 
LIMIT 10
于 2013-09-27T14:36:10.063 回答