/*使用子查询,只返回从表的一条数据的id,可以看到主表f=1时从表返回id最小的的数据,
主表f=0时从表随机返回一条数据。查询结果见下表。
但这种方法子查询语句只能返回一个字段,
如果把SELECT t2.id FROM s2 t2改成SELECT * FROM s2 t2,
会报错Error Code: 1241. Operand should contain 1 column(s)
*/
SELECT t1.* ,(SELECT t2.id FROM s2 t2 order by
(case when t1.f=0 then rand()else t2.id end)
limit 1) id2 FROM s2 t1 order by t1.id;
id
a
b
f
id2
1
1
1
1
1
2
2
2
0
2
3
1
3
1
1
4
3
4
0
2
5
3
5
1
1
6
2
6
0
4
7000
5
6
1
1
/*修改上面的写法,只返回主表和从表的id生成临时表。
然后再连接两表+临时表取全部数据。
*/
select q1.*,q2.* from s2 q1,s2 q2,(SELECT t1.id id1,(SELECT t2.id FROM s2 t2 order by
(case when t1.f=0 then rand()else t2.id end)
limit 1)
id2 FROM s2 t1) q3
where q1.id=q3.id1 and q2.id=q3.id2 order by q1.id;
ab两表关联查询,a有个flg字段,对于a的每条数据b有0-n条数据,要求b只返回一条数据,如果a的某fl为true,则返回b的id最小的数据;如果a的某flg为false,则随机返回b的一条数据。使用表t2进行自连接测试,数据如下SELECT * FROM s2;idabf111122203131434053...