[英]Where clause for only one table in a left join
我有兩個表,第一個是“ actions”,具有“ id”和“ actionname”列,第二個表是“ completedactions”,具有“ userid”和“ actionid”。 它們看起來如下:
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子句,那么我應該怎么做呢?
嘗試在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)
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
從動作中選擇*
在(completedactions.actionid = actions.id和completedactions.userid = 1)上左外部聯接completedactions
如果有人需要使用它,它將為您提供全面的幫助。
select `m`.`id` AS `id`,
`m`.`CategoryParentId` AS `CategoryParentId`,
`m`.`CategoryChildId` AS `CategoryChildId`,
`p`.`CategoryName` AS `ParentCategory`,
`c`.`CategoryName` AS `ChildCategory`,
count(c_p.category_id) AS `prodcuts`,
`img`.`image` AS `CategoryImage`,
`img2`.`image` AS `thumbImage`
from (((((`tblcategoryparentchildassociations` `m`
left join `tblmastercategories` `c` on((`c`.`id` = `m`.`CategoryChildId`)))
left join `tblmastercategories` `p` on((`p`.`id` = `m`.`CategoryParentId`)))
left join `vwimagetypeassociations` `img` on((`c`.`id` = `img`.`domainid` AND `img`.`imagetypeid` = 2 AND `img`.`status` = 1 )))
left join `vwimagetypeassociations` `img2` on((`c`.`id`= `img`.`domainid`AND `img2`.`imagetypeid` = 3 AND `img`.`status` = 1)))
left join `tblproductcategoriesassociations` `c_p` on((`m`.`CategoryChildId` = `c_p`.`category_id`)))
group by m.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.