我需要一个子选择吗?

时间:2013-08-23 12:13:09

标签: mysql sql

我的两张表是:

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

我想列出那些预订目的地=“希腊”的用户的所有预订;

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]

[...]

我是更复杂的SQL的新手。我认为你需要一个子选择。但它是如何运作的?

2 个答案:

答案 0 :(得分:0)

可能最简单的方法是将逻辑放在where子句中:

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

在早期版本的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;

如果您想要用户汇总的信息,您可以通过这种方式将目的地列表放在一个字段中:

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;

答案 1 :(得分:0)

我是通过加入来做的:

逻辑是,在子查询中,您为具有匹配预订的用户检索用户ID。

您使用该ID列表再次加入预订表。因此,这将为您提供符合您的第一个标准的所有用户的列表。

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

PS:

正如@Kickstart在评论中指出的那样,您需要在子查询中添加SELECT DISTINCT useridGROUP BY userid。否则你很可能会重复行。