2014-05-09 35 views
0

所以我有這些表。選擇使用SQL子查詢或JOIN子句

此表存儲喜歡:

Table Name: Action 

Id Creator Type Target  <--- The `Target` here is the `Id` in Posts 
1 1   like 1 
2 2   like 1 
3 3   like 1 
4 1   like 2 

此表存儲的帖子:

Id Creator 
1 1 
2 2 

列名Creator在任何表是指在Account表(這裏沒有顯示)的Id列。

我想選擇一個帳戶的帖子喜歡的總數。 我已經嘗試了下面的查詢,但它給了一個語法錯誤。

SELECT count(`Id`) AS Check FROM `Action` WHERE `Type`='like' AND `Target`= (SELECT `Id` FROM `Posts` WHERE `Creator` = '1'); 

我不確定在這裏JOIN子句是否更合適。

+0

您可以構建一個查詢,只返回所有候選行(應計的結果)?如果沒有,您可能需要閱讀有關JOIN的信息 – Strawberry

回答

1

您將得到兩個表和GROUP BY加入的總和並計算出合適的目標。

SELECT 
    p.creator,  
    COUNT(a.target) 
FROM 
    posts p 
INNER JOIN 
    Action a 
ON 
    a.target = p.id 
WHERE 
    a.Type = 'like' AND p.creator = 1 
GROUP BY 
    p.creator; 
+0

這很好,但我要求特定帳戶中的喜歡總數。 – ThePixelPony

+0

只需將它添加到where子句中,就像我在編輯中所做的那樣。 – VMai

0

這裏是SQL



    select a.ID,a.Creator,a.Type,a.Target, Count(p.*)Total 
    from Action a 
    join posts p on a.Target=p.Creator 
    where 
    a.Type='like' 
    and a.Target=1;