0

我的两张表是:

 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 的新手。我认为你需要一个子选择。但它是如何工作的?

4

2 回答 2

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;
于 2013-08-23T12:16:45.713 回答
0

我会用 JOIN 来做:

逻辑是在子查询中检索具有匹配预订的用户的用户 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 在评论中指出的那样,您需要在子查询中添加 aSELECT DISTINCT userid或 a GROUP BY userid。否则你很可能会得到重复的行。

于 2013-08-23T12:20:35.913 回答