[英]Do I need a subselect?
我的两个表是:
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的新手。 我认为您需要为此进行子选择。 但是它是如何工作的呢?
可能最简单的方法是将逻辑放在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;
我可以用JOIN来做到:
逻辑是,在子查询中,您将为具有匹配预订的用户检索用户ID。
您使用该ID列表再次与Bookings表联系。 因此,这将为您提供符合您的第一个条件的所有用户的列表。
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 userid
或GROUP BY userid
。 否则,您很可能会得到重复的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.