Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 来自同一表的子查询_Mysql_Subquery - Fatal编程技术网

Mysql 来自同一表的子查询

Mysql 来自同一表的子查询,mysql,subquery,Mysql,Subquery,表结构 [place] p.place_id p.name p.image p.address p.phone p.website p.description p.lng p.lat p.distance p.last_update p.is_ad SELECT DISTINCT p.* FROM place p 我需要选择所有记录,其中包含2个随机记录,标志为_ad=1 例如: 记录: 1 is_ad 0 2 is_ad 1 3 is_ad 0 4 is_ad 1 5 is_ad 0 6

表结构

[place]
p.place_id
p.name
p.image
p.address
p.phone
p.website
p.description
p.lng
p.lat
p.distance
p.last_update
p.is_ad

SELECT DISTINCT p.* FROM place p
我需要选择所有记录,其中包含2个随机记录,标志为_ad=1

例如:

记录:

1 is_ad 0
2 is_ad 1
3 is_ad 0
4 is_ad 1
5 is_ad 0
6 is_ad 1
7 is_ad 0
在第一个位置随机显示两条记录

1 is_ad 1 
6 is_ad 1
3 is_ad 0
4 is_ad 0
5 is_ad 0
7 is_ad 0
7 is_ad 0
它应该显示在第一个位置

1 is_ad 1 
6 is_ad 1
3 is_ad 0
4 is_ad 0
5 is_ad 0
7 is_ad 0
7 is_ad 0

谢谢。

您可能需要稍微更新一下预期结果:7存在,0存在两次;1 is_ad 0已更改为1 is_ad 0,2 is_ad 1已丢失,4 is_ad 1也已更改为4 is_ad 0。您可以使用sql函数rand执行此操作。例如,从表中选择*其中is_ad=1 ORDER by rand
(SELECT * FROM place where is_ad = 1 order by rand() limit 2)
union all
(SELECT * FROM place where is_ad <> 1 order by place_id)