基于这篇文章,我得到了这个查询,从一个组(块)中选择随机记录。 (有关背景,请参阅Select random record within groups sqlite) 但我意识到我需要排除新字段“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'
给出以下数据
id|link|chunk|qcinfo
2|Yes|me1|Y
3|rr|me1|
4|yy|me1|
5|uu|you2|
6|Yes|you2|Y
7|waw|you2|
8|wewe|you2|
9|eff|you2|
10|wefw|him3|
11|Yes|him3|Y
12|we|him3|
13|wefr|him3|
以下(注释注释行)给出了我需要但不排除Y.当我在子查询中包含WHERE时,我没有得到任何记录,我无法弄清楚原因。
select t.chunk ,t.id, t.qcinfo, t.link from marlintag t
inner join
(
select chunk ,cast(min(id)+abs(random() % (max(id)-min(id)))as int) AS random_id
from marlintag
-- where qcinfo <> 'Y'
group by chunk ) sq
on t.chunk = sq.chunk
and t.id = sq.random_id
答案 0 :(得分:1)
将WHERE子句移动到子查询。
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
where qcinfo <> 'Y'
group by chunk
) sq
on t.chunk = sq.chunk
and t.id = sq.random_id