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. 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?
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.
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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With