2015-04-30 31 views
2

我有兩個表。在一個查詢中使用select和count函數從表中獲取數據

user_circle 

user_id circle_id user_type_id 
1  1   1 
1  2   1 
1  3   1 
1  4   2 
2  2   2 


user_type 

id type 
1 admin 
2 member 

我不得不從user_circle表獲取所有circle_id其中user_id = 1user_type_id = 1和「member」(即號碼:那circle) in that circle`的admin是一個

我需要一個像結果

circle_id 
1 
3 

我怎樣才能做到這一點?它可以在一個查詢做?

+0

在結果中我I認爲它意味着「在該圈子中'成員'的數量是*不*一個」;)。 –

回答

0

,我可以看到你的結果也關係到所有circle_id有沒有成員,所以你需要這個結果:

SELECT DISTINCT uc.circle_id 
FROM user_circle uc 
WHERE uc.circle_id NOT IN (
    SELECT uci.circle_id 
    FROM user_circle uci 
    WHERE uci.user_type_id = 2) 

    AND uc.user_id = 1 AND uc.user_type_id = 1 

向上述改變代碼爲DELETE聲明:

DELETE FROM user_circle uc 
WHERE uc.circle_id NOT IN (
    SELECT uci.circle_id 
    FROM user_circle uci 
    WHERE uci.user_type_id = 2) 
    AND uc.user_id = 1 AND uc.user_type_id = 1 
+1

我該如何刪除這些查詢中的circle_id?是否必須運行其他查詢以刪除這些circle_id,或者可以使用DELETE子句而不是SELECT來在回答中寫入的相同查詢中完成此操作。 PLZ響應。 –

+0

@Deepakkumar只需刪除'SELECT'部分;)。 –

+0

是。 thanx男人。 –

0

你將需要使用一個組。事情是這樣的:

SELECT circle_id 
FROM 
    (SELECT circle_id, user_type_id, count(*) AS total 
    FROM user_circle 
    WHERE user_id = 1 and user_type_id = 1 
    GROUP BY user_type_id, circle_id 
) t 
WHERE total = 1 
+0

我試過你的查詢。但是它返回了我的所有circle_id,其中user_id = 1和user_type_id = 1。我還需要其中只有一個成員的circle_id。 –

相關問題