[英]SQL select one row from table 1 joining on multiple rows in table 2
所以我有兩個表,第一個是 users_
Name
------
Carol
Sue
第二個是興趣_
Name Interest
----------------------
Carol Books
Carol Dancing
Carol Sports
Sue Books
Sue Dancing
用戶將看到復選框以根據類似興趣的標准選擇匹配項
因此,如果用戶選擇書籍和舞蹈作為他們的比賽興趣,我將構建什么類型的 sql 查詢來組合多行興趣並確保結果是 Sue,因為她的興趣是書籍和舞蹈而不是體育?
任何幫助都會大有幫助,謝謝!
所以基本上要做到這一點,請建立一個負面列表,列出擁有超過這兩個的用戶,然后選擇其他用戶
SELECT u.name
FROM users_ u
JOIN interests_ i ON i.name = u.name
JOIN
( SELECT u.name
FROM users_ u
JOIN interests_ i ON i.name = u.name
WHERE i.interest NOT IN('Books', 'Dancing')
) t
WHERE u.name <> t.name
AND i.interest IN('Books', 'Dancing')
GROUP BY u.name
HAVING COUNT(u.name) = 2;
這是執行此操作的簡單方法
select
i.name
from interests i
where i.interest in ('Books','Dancing')
and not exists
(
select 1 from interests i1
where interest not in ('Books','Dancing')
AND i.name = i1.name
)
group by i.name
having count(*) = 2
實現此結果的一種方法:
SELECT u.name
FROM users_ u
JOIN interests_ n01 ON n01.name = u.name AND n01.interest = 'Books'
JOIN interests_ n02 ON n02.name = u.name AND n02.interest = 'Dancing'
LEFT JOIN interests_ x01 ON x01.name = u.name AND x01.interest = 'Sports'
LEFT JOIN interests_ x02 ON x02.name = u.name AND x01.interest = 'Wine'
WHERE x01.name IS NULL
AND x02.name IS NULL
這種方法要求“包含”每個興趣的 JOIN,以及“排除”每個興趣的反聯接。 這種方法是靈活的,但對於大量利益來說可能變得笨拙。
要僅查找指定興趣的匹配項,而不必列出所有不匹配的興趣,我們可以使用反聯接查找不匹配的興趣行:
SELECT u.name
FROM users_ u
JOIN interests_ n01 ON n01.name = u.name AND n01.interest = 'Books'
JOIN interests_ n02 ON n02.name = u.name AND n02.interest = 'Dancing'
LEFT
JOIN interests_ o
ON o.name = u.name
AND o.interest NOT IN ('Books','Dancing')
WHERE o.name IS NULL
另一種方法是利用 JOIN 操作和COUNT()
聚合,例如
SELECT u.name
FROM users_ u
JOIN interests_ n
ON n.name = u.name
AND n.interest IN ('Books','Dancing')
LEFT
JOIN interests_ o
ON o.name = u.name
AND o.interest NOT IN ('Books','Dancing')
WHERE o.name IS NULL
GROUP BY u.name
HAVING COUNT(DISTINCT n.interest) = 2
還有一些其他方法(這些只是一些示例)。
in
操作符中使用 SQL
select * from interests_ where Interest in ('Books', 'Dancing') and Interest not in ('Sports');
編輯 1
這對我有用
SELECT * FROM user_ WHERE EXISTS (
SELECT i.Name, count(distinct i.Interest) FROM interests_ as i
WHERE i.Name=user_.Name
AND i.Interest IN ('Books','Dancing')
GROUP BY i.Name
HAVING count(distinct i.Interest) = 2
);
左連接非常有用。 你可以試試這個。
SELECT users_.*
FROM users_
LEFT JOIN interests_
ON users_.Name = Interests_.Name
WHERE interests_.Interests = 'Books'
AND interests_.Interests = 'Dancing'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.