2013-12-20 37 views
2

我願做以下查詢:SQL查詢和訪問另一個表

計數的人通過特定的屬性#,但只有當他們已經做了我的網站上的特定操作。

通過屬性來算的人#:

select attribute, count(*) from users group by attribute

目前,特定行動爲存儲在表Y.

,所以我想執行只有在這個特定的用戶數在表Y中有一個條目。用戶將按ID存儲。所以基本上我想要做的是;

select attribute, count(*) from users group by attribute IF Y has user_id of user

回答

0

由於Barmar指出,我們不想多行,如果我們用一個簡單的連接發生。 因此,我們製作一個臨時表來加入不同的ID。

select attribute, count(*) from users as u, 
(select distinct user_id from Y) as Y2 
where U.user_id = Y2.user_id 
group by attribute; 
+0

這將給出錯誤的答案,如果用戶在Y. – Barmar

+0

由於多個條目,我已經使用臨時表相應的修改。 –

0
SELECT attribute, COUNT(*) 
FROM USERS AS u 
JOIN (SELECT DISTINCT user_id 
     FROM Y) AS y 
ON u.user_id = y.user_id 
GROUP BY attribute 

或:

SELECT attribute, COUNT(*) 
FROM users 
WHERE user_id in (SELECT user_id FROM y) 
GROUP BY attribute 
+0

存在比使用IN進行搜索快得多。 –

+0

這可能取決於SQL的實現。無論如何,我通常使用'JOIN',因爲它在MySQL中通常更快。 – Barmar

+0

對於使用IN的少數記錄會更快,但是如果大記錄然後使用Exists會比IN更好 – Jade