左连接中只有一个表的Where子句

时间:2014-02-28 19:35:42

标签: mysql

我有两个表,第一个是'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子句,所以我应该怎么做呢?

4 个答案:

答案 0 :(得分:3)

尝试使用WHERE条款中的ON()条件,即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 :(得分: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

答案 2 :(得分:0)

从行动中选择*

left outer join completedactions on(completedactions.actionid = actions.id and completedactions.userid = 1)

答案 3 :(得分:0)

如果有任何人需要使用它,它将会有所帮助。

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