Mysql LEFT JOIN没有返回预期的结果

时间:2014-04-25 16:39:08

标签: mysql

我正在尝试使用以下4个表创建LEFT JOIN。 我们的想法是显示userid的parent.name.Should groupconcat子名,如果用户不在子users表中,则child.name应为NULL

以下是用户ID 1的预期结果:

  id     parentname    childname
-------------------------------------------------
  1        parent1      child1,child3

以下是用户ID 2的预期结果: 这个用户不在childusers表中,所以它应该返回null

  id     parentname    childname
-------------------------------------------------
  1        parent2      NULL

表:

 id        parentname
--------------------------------------------
  1        parent1
  2        parent2
  3        parent3

  id        childname     parent_id
-----------------------------------------------
  1         child1       1
  2         child2       2
  3         child3       1

parentusers

  id        parent_id    user_id
-------------------------------------------------------
  1            1           1
  2            2           2
  3            3           1

childusers

  id        child_id    user_id
-------------------------------------------------------
  1            1           1

这是我的问题:

 SELECT parent.name AS parentname,
 GROUP_CONCAT(child.name SEPARATOR ',') AS childname
 FROM parentusers,parent
 LEFT JOIN child
 ON parent.id=child.parent_id
 WHERE parentusers.parent_id= parent.id
 AND parentusers.user_id='1'
 GROUP BY parent.id

我已经编写了两个单独的查询,但希望将这两个结合在上面提到的结果格式的单个结果中。

 select parent.parentname from parent,parentusers
 where parent.id=parentusers.parent_id
 and parentusers.user_id=1 ;

 select GROUP_CONCAT(child.childname) as childname from child
 LEFT JOIN childusers
 ON child.id=childusers.child_id
 where childusers.user_id=1;

谢谢..

2 个答案:

答案 0 :(得分:0)

我在您的查询中看到以下错误:

  1. 语法错误(额外的逗号)bofore FROM子句。

  2. 您将表child的别名命名为sub,然后您尝试加入child.parent_id

  3. 试试这个:

    SELECT parent.name AS parentname, IFNULL(GROUP_CONCAT(child.name),'') AS childname
    FROM parentusers LEFT JOIN 
         parent ON parentusers.parent_id=parent.id LEFT JOIN 
         child sub ON parent.id=sub.parent_id
    WHERE parentusers.user_id='1'
    GROUP BY parent.id
    

    我做的修改(错误纠正除外):

    1. 使用LEFT JOIN加入表格parentusersparent

    2. 添加了IFNULL,如果GROUP_CONCAT为空,则会返回一个空字符串。

答案 1 :(得分:0)

最后,我从以下查询获得了预期的结果

SELECT * FROM (SELECT parent.parentname AS parentname, 
parent.id AS parentid 
FROM parent,parentusers
WHERE parent.id=parentusers.parent_id
AND parentusers.user_id='2') parentdata
LEFT JOIN
(SELECT GROUP_CONCAT(child.childname SEPARATOR ',') AS childname,
GROUP_CONCAT(child.id SEPARATOR ',') AS childid
FROM parent

LEFT JOIN parentusers
ON parent.id=parentusers.parent_id

LEFT JOIN child
ON child.parent_id=parent.id
AND child.parent_id=parentusers.parent_id

LEFT JOIN childusers
ON child.id=childusers.child_id

AND childusers.user_id=parentusers.user_id
WHERE childusers.user_id='2' 
GROUP BY parent.id ) childdata
ON parentdata.parentid=childdata.childid

http://sqlfiddle.com/#!2/8ffaa/50