我似乎无法理解这一点。我在 SQlite 中有一个表,我需要从中选择一个 random()
每个组的记录。因此,考虑一个表,例如:
id link chunk
2 a me1
3 b me1
4 c me1
5 d you2
6 e you2
7 f you2
我需要 sql 为每个块返回一个随机链接值。所以有一次我运行它会给出:
me1 | a
you2 | f
下一次也许
me1 | c
you2 | d
我知道已经回答了类似的问题,但我没有找到适用于此的推导。
更新:
坚果,跟进问题:所以现在我需要排除新字段“qcinfo”设置为“Y”的行。
这当然会在随机 ID 遇到 qcinfo = 'Y' 时隐藏行,这是错误的。我需要从块中排除该行,但如果任何记录具有 qcinfo <> 'Y',仍会为块生成随机记录。
select t.chunk ,t.id, t.qcinfo, t.link from table1
inner join
(
select chunk ,cast(min(id)+abs(random() % (max(id)-min(id)))as int) AS random_id
from table1
group by chunk
) sq
on t.chunk = sq.chunk
and t.id = sq.random_id
where qcinfo <> 'Y'
最佳答案
有点hackish,但它有效......参见sql fiddle http://sqlfiddle.com/#!2/81e75/7
select t.chunk
,t.link
from table1 t
inner join
(
select chunk
,FLOOR(min(id) + RAND() * (max(id)-min(id))) AS random_id
from table1
group by chunk
) sq
on t.chunk = sq.chunk
and t.id = sq.random_id
抱歉,我以为你说的是 MySQL。
这是 SQLite 的 fiddle 和代码
http://sqlfiddle.com/#!5/81e75/12
select t.chunk
,t.link
from table1 t
inner join
(
select chunk
,cast(min(id)+abs(random() % (max(id)-min(id)))as int) AS random_id
from table1
group by chunk
) sq
on t.chunk = sq.chunk
and t.id = sq.random_id
关于sql - 在组 sqlite 中选择随机记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003074/