简体   繁体   English

右连接无法正常工作

[英]right join does not work properly

I have two tables as follow:我有两个表如下:

在此处输入图片说明

when I use the following command I get the following result:当我使用以下命令时,我得到以下结果:

SELECT A.enid AS enid, sum(A.comment) AS Comments, B.enname
FROM ee.entity_epoch A
right JOIN ee.entity B
ON A.id = B.enid group by A.enid

Result:结果:

在此处输入图片说明

But according to the following link:但根据以下链接:

joins since I use right join I expect to get the records for saman and reza with column of comment as null. 加入,因为我使用了正确的加入,我希望得到 saman 和 reza 的记录,注释列为空。 I am so confused can anyone says how can I get records with saman and reza and null for comment column plus the result shown above?我很困惑,谁能说我怎样才能获得 saman 和 reza 的记录,以及评论列的 null 以及上面显示的结果?

reza and saman both have matches in A, so no "Comments is NULL" records from A are generated for them. reza 和 saman 在 A 中都有匹配项,因此不会为它们生成来自 A 的“Comments is NULL”记录。 Are you sure you didn't want你确定你不想

SELECT A.enid AS enid, sum(A.comment) AS Comments, B.enname FROM ee.entity_epoch A right JOIN ee.entity B ON A.enid = B.enid group by A.enid

? ?

I think you want a subquery here before the join.我认为您在加入之前需要一个子查询。

SELECT *
  FROM (SELECT enid
             , SUM(COMMENT) AS Comments
          FROM entity_epoch
          GROUP BY enid) a
        RIGHT JOIN
        entity B ON A.enid = B.enid

sqlfiddle sqlfiddle

Personally I would reorder and make it a left join for readability, but it doesn't make any functional difference.就个人而言,我会重新排序并使其成为可读性的左连接,但它不会产生任何功能差异。

This can also be done as:这也可以这样做:

SELECT A.enid AS enid
      ,SUM(A.Comment) Comments
      , B.enname
  FROM entity_epoch A
       RIGHT JOIN 
       entity B
       ON A.enid = B.enid 
GROUP BY b.enid

sqlfiddlee sqlfiddlee

I'd be curiosu to see the different in exectuon plan, but don't have MySQL available.我很想知道执行计划中的不同之处,但没有可用的 MySQL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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