简体   繁体   中英

Do I need a subselect?

My two tables are:

 table User ( userid,  username,  ... )
 table Bookings ( bookingid, userid, destination, ...) 

I want to list all Bookings by those users who have a booking where destination = "Greece";

first match: (user name) 
  Destination: Greece ( = match criteria) 
  Destination: [other destinations from this user]
  Destination: destionation n ...

second match: (user name) 
  Destination: Greece 
  Destionation: [other destionations]

[...]

I am new to more complex SQL. I think you need a subselect for this. But how does it work?

Probably the simplest way to do this is to put the logic in the where clause:

select b.*
from bookings b
where b.userid in (select b2.userid from bookings b2 where b2.destination = 'Greece')
order by b.userid;

In earlier versions of MySQL, this will be more efficient using exists :

select b.*
from bookings b
where exists (select 1 from bookings b2 where b2.userid = b.userid and b2.destination = 'Greece')
order by b.userid;

If you want the information summarized by user, you can put the list of destinations in a single field this way:

select u.*, group_concat(b.destination) as destinations
from users u join
     bookings b
     on u.userid = b.userid
group by u.userid
having sum(b.destination = 'Greece') > 0;

I'd do it with a JOIN:

The logic is that in the subquery you retrieve the userid's for users that have a matching booking.

The you use that list of id's to join again with the bookings table. So, this will get you a list of all the users that match your first criterion.

SELECT b.* 
FROM Bookings b
INNER JOIN (
    SELECT userid
    FROM Bookings
    WHERE destination = "Greece"
    GROUP BY userid
) aux ON aux.userid = b.userid

PS:

As @Kickstart points out in a comment, you need to add a SELECT DISTINCT userid or a GROUP BY userid in the subquery. Otherwise you will most likely get repeated rows.

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