Mysql Left加入多个条件

时间:2013-12-09 13:39:14

标签: mysql join left-join

我有两张表格如下: 用户表:

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
    PRIMARY KEY (`id`)      
);

另一张表如下:

CREATE TABLE `uep` (
  `user_id` int(10) unsigned NOT NULL,
  `email_template_id` int(10) unsigned NOT NULL,
  `sid` int(10) unsigned NOT NULL,
  `send_email` tinyint(1) NOT NULL DEFAULT '1'
);

我想从用户表中获取所有记录,并且只有当left加入uep表时才会 user.id = uep.user_id AND uep.send_email = 0

但是当我运行查询

Select id, group_concat(email_template_id) as T from user
LEFT join uep ON (user.id = uep.user_id AND uep.send_email = 0)
group by user_id limit 100

它忽略了具有send_email = 1的用户表中的用户。

我想只在user.id和send_email = 0时加入uep表,否则它不应该加入并仅返回用户详细信息。

Sql Fiddle:http://www.sqlfiddle.com/#!2/1f083/2

任何有用的帮助!

5 个答案:

答案 0 :(得分:2)

尝试

Select 
    id, group_concat(email_template_id) as T 
from 
    user
LEFT join 
    uep 
ON 
  (user.id = uep.user_id AND uep.send_email = 0)
OR
  (uep.send_email = 1 AND user.id = uep.user_id)
group by 
  user_id 
limit 
  100;

演示http://www.sqlfiddle.com/#!2/6c28ee/1

答案 1 :(得分:1)

由于“分组依据”条件,您的查询返回错误结果。只需按user_id将group更改为id,如下所述:

Select id, group_concat(email_template_id) as T from user
LEFT join uep ON (user.id = uep.user_id AND uep.send_email = 0)
group by id limit 100

答案 2 :(得分:0)

你在帖子中提到它忽略了send_email = 1的用户。它应该有它们,因为用户是连接的LEFT基础,但是,它的“T”值将为空,因为你的LEFT-JOIN只关心0值。那么,你想要什么...两列?一个发送电子邮件= 0,另一个发送电子邮件= 1?

Select 
      u.id, 
      COALESCE( UEP0.T, '' ) T,
      COALESCE( UEP1.T, '' ) T1
   from 
      user u
         LEFT join ( select uep.user_id,
                            group_concat( uep.email_template_id ) as T
                        from
                           uep
                        where
                           uep.send_email = 0
                        group by
                           uep.user_id ) UEP0
            ON (u.id = UEP0.user_id)
         LEFT join ( select uep.user_id,
                            group_concat( uep.email_template_id ) as T
                        from
                           uep
                        where
                           uep.send_email = 1
                        group by
                           uep.user_id ) UEP1
            ON (u.id = UEP1.user_id)
   limit 
      100

此版本获得两个版本...左连接分别与UEP表一起为各自的send_email状态为0或1执行自己的组concat()。因此,用户表连接到BOTH结果并获取任一版本,现在,您可以使用相应的模板ID执行所需的操作。

答案 3 :(得分:-1)

您不必将其包含在ON子句中。您只需添加WHERE子句:

Select id, group_concat(email_template_id) as T from user
LEFT join uep ON (user.id = uep.user_id)
WHERE uep.send_email = 0
group by user_id limit 100

答案 4 :(得分:-1)

抱歉,现在没时间做小提琴了,但是这样的事情对你有用。

Select id, u2.T from user
LEFT join 
( Select `user_id`, group_concat(email_template_id) as T 
  From uep
  Where uep.send_email = 0
) u2
On user.id = u2.user_id 
group by user_id limit 100