[英]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.