2011-01-21 51 views
10

我有什麼似乎是一個簡單的問題,但不能通過SQL找出適當的解決方案。我特別使用postgresql。SQL查詢連接中的所有記錄是否與條件匹配?

採取以下:

SELECT * FROM users INNER JOIN tags ON (tags.user_id = users.id) WHERE tags.name IN ('word1', 'word2') 

這沒有做什麼,我需要。我想查找其標籤僅包含在列表中的用戶。如果用戶的標籤不在列表中,則不應包含該用戶。

'user1的' 標籤:字詞1,word2和WORD3
'user2的' 標籤:字1
'用戶3' 標籤:字1,單詞2

鑑於:字詞1和字詞2。我想準備一個返回'user2'和'user3'的查詢。 'user1'被排除,因爲它有一個不在列表中的標籤。

希望我明確表達了這一點。謝謝你的幫助!

+2

可能重複[?SQL,如何搭配ALL](http://stackoverflow.com/questions/4763143/sql-how-to-match -all) – 2011-01-21 23:00:37

+0

難道你只是問這個 – 2011-01-21 23:00:48

+0

應該沒有標籤的用戶被退回嗎? – Quassnoi 2011-01-21 23:13:06

回答

6

依靠COUNT(*)= 2將要求在tag表中不能有user_id和name的重複。如果是這樣的話,我會走那條路。否則,這應該工作:

SELECT u.* 
FROM users AS u 
WHERE u.id NOT IN (
    SELECT DISTINCT user_id FROM tags WHERE name NOT IN ('word1', 'word2') 
) AND EXISTS (SELECT user_id FROM tags WHERE user_id = u.id) 
1
SELECT user_id 
FROM users 
WHERE id IN 
     (
     SELECT user_id 
     FROM tags 
     ) 
     AND id NOT IN 
     (
     SELECT user_id 
     FROM tags 
     WHERE name NOT IN ('word1', 'word2') 
     ) 

SELECT u.* 
FROM (
     SELECT DISTINCT user_id 
     FROM tags 
     WHERE name IN ('word1', 'word2') 
     ) t 
JOIN users u 
ON  u.id = t.user_id 
     AND t.user_id NOT IN 
     (
     SELECT user_id 
     FROM tags 
     WHERE name NOT IN ('word1', 'word2') 
     ) 
0

爲了讓那些沒有標記不在列表中的所有用戶,使用下面的查詢。可能是返回的用戶沒有標籤或只有一個標籤匹配單詞,但我知道這是所需的功能。

SELECT 
    u.* 
FROM 
    users u 
    LEFT JOIN tags t 
    ON t.user_id = u.userid AND 
     t.name NOT IN ('word1', 'word2') 
WHERE 
    t.user_id IS NULL 
0
SELECT u.* 
FROM users u 
INNER JOIN (
    SELECT user_id FROM tags WHERE name IN ('word1', 'word2') 
    EXCEPT 
    SELECT user_id FROM tags WHERE name NOT IN ('word1', 'word2') 
) s ON u.id = s.user_id 
0
SELECT distinct users.id 
FROM users 
INNER JOIN tags ON (tags.user_id = users.id) 
group by users.id 
having count(*) = 2 
and min(tags.name) = 'word1' 
and max(tags.name) = 'word2' 
相關問題