简体   繁体   中英

Subquery from the same table

TABLE STRUCTURE

[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

I need to select all records, which contains 2 RANDOM records with flag "is_ad" = 1

so for ex:

Record:

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

show random two records first position

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

it should show at first position

Thank you.

(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM