我面临一些不寻常的问题。请帮忙。一列有 300 行。我想通过 rand() 显示任何 100 个订单。但在这随机选择的 100 个中,必须有 2 行。我该怎么写?例子:
“从 sample_table 中选择 id,其中 id<300 或 id>1 order by rand() limit 100”
但我希望结果必须包含 id=34 和 id=78
我面临一些不寻常的问题。请帮忙。一列有 300 行。我想通过 rand() 显示任何 100 个订单。但在这随机选择的 100 个中,必须有 2 行。我该怎么写?例子:
“从 sample_table 中选择 id,其中 id<300 或 id>1 order by rand() limit 100”
但我希望结果必须包含 id=34 和 id=78
使用 UNION ALL 选择结果中必须存在的 2 行和 98 个随机行:
select id from sample_table
where id in (34, 78)
union all
select id from (
select id from sample_table
where where id not in (34, 78)
order by rand() limit 98
) t
order by rand()
或更简单的条件排序:
select * from (
select id from sample_table
order by id not in (34, 78), rand()
limit 100
) t
order by rand()
与原始 SELCT 联合并随机该联合的结果
SELECT
id
FROM
(SELECT 34 UNION SELECT 78 UNION SELECT
id
FROM
sample_table
WHERE
id < 300 OR id > 1
ORDER BY RAND()
LIMIT 98)
ORDER BY RAND()