Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right join does not work properly

Tags:

sql

mysql

I have two tables as follow:

enter image description here

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:

enter image description here

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. 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?

like image 218
HMdeveloper Avatar asked Jul 01 '26 20:07

HMdeveloper


2 Answers

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

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

I'd be curiosu to see the different in exectuon plan, but don't have MySQL available.

like image 57
Karl Kieninger Avatar answered Jul 04 '26 08:07

Karl Kieninger


reza and saman both have matches in A, so no "Comments is NULL" records from A are generated for them. 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

?

like image 20
user2781942 Avatar answered Jul 04 '26 09:07

user2781942