简体   繁体   English

我需要子选择吗?

[英]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. 我是更复杂的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: 可能最简单的方法是将逻辑放在where子句中:

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 : 在早期的MySQL版本中,使用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: 我可以用JOIN来做到:

The logic is that in the subquery you retrieve the userid's for users that have a matching booking. 逻辑是,在子查询中,您将为具有匹配预订的用户检索用户ID。

The you use that list of id's to join again with the bookings table. 您使用该ID列表再次与Bookings表联系。 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: PS:

As @Kickstart points out in a comment, you need to add a SELECT DISTINCT userid or a GROUP BY userid in the subquery. 正如@Kickstart在注释中指出的那样,您需要在子查询中添加SELECT DISTINCT useridGROUP BY userid Otherwise you will most likely get repeated rows. 否则,您很可能会得到重复的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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