2014-02-28 42 views
2

我有兩個表,第一個是'actions',它有'id'和'actionname'列,第二個是'completedactions',它具有'userid'和'actionid' 。他們看起來如下:Where子句只有一個表在左連接

Table: actions 

id | actionname 
============== 
    1 | An action 
    2 | Another 
    3 | ect 
    4 | ect 

actions is a table of actions a user can make 

-

Table: completedactions 

userid | actionid 
============== 
    1 | 1 
    1 | 2 
    1 | 3 
    2 | 3 
    3 | 2 
    3 | 4 

completedactions holds the userid and action id for each action made 

我想加入的表給所有操作的列表以及這些動作已經由給定用戶所做的,在某個指定的查詢。所以從這個例子,我想看到的東西,如:

id | actionname | Complete by userid=1? 
======================================= 
    1 | An action | 1 
    2 | Another | 1 
    3 | ect  | 1 
    4 | ect  | Null 

我已經嘗試了左連接,並設法讓所有操作的列表,但有多個用戶已採取的行動的重複條目,一個用於每個用戶做出行動。然後我在compledtedactions.userid =「1」的末尾添加了where子句,但是然後我失去了該用戶尚未完成的所有操作。

我似乎無法在左連接中只有一個表的where子句,所以我該怎麼處理這個問題?

回答

3

請嘗試在您的ON()條款中使用您的WHERE條件,即ON (c.actionid = a.id AND c.user_id = 1)

WHERE過濾器將應用於整個結果集,而連接中的附加條件將加入匹配結果並給出null以獲得不匹配的結果。

SELECT a.*,c.user_id FROM 
actions a 
LEFT JOIN completedactions c 
ON (c.actionid = a.id AND c.user_id = 1) 
+1

我要發佈一個答案,但我只需鏈接這個SQL小提琴:http://sqlfiddle.com/#!2/bf162/4 –

0
select 
    actions.id, 
    actions.actionname, 
    count(completedactions.actionid) 
from actions 
left join completedactions 
    on completedactions.actionid = actions.id and completedactions.userid = 1 
group by 1,2 
0

SELECT * FROM行動

左外連接completedactions上(completedactions.actionid = actions.id和completedactions.userid = 1)