繁体   English   中英

左联接中仅一个表的where子句

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM