Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: FULL Outer Join Not Working [duplicate]

I have two tables, one of them is empty but the other isn't.

  • hugot_votes_stats : http://prntscr.com/72ft7d
  • hugot_comment_stats: Empty

I understand that I can't use Inner JOIN because it will only matches the value as specified in the ON part. In this case one table has no value.

SELECT  t0.hugot_id                     as hugot_id,
        t0.upvotes                      as upvotes,
        t1.comment_count                as comment_count
FROM
    hugot_votes_stats as t0
FULL OUTER JOIN
    hugot_comment_stats as t1
ON
    t0.hugot_id = t1.hugot_id

This is the part I figured using FULL JOIN. What I was expecting is that empty tables (in this case the comment_count) will show a default value (i.e: 0) if there is none found.

Yet I am given an error as you can see 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

like image 604
Mr A Avatar asked May 07 '15 04:05

Mr A


People also ask

Does full outer join produce duplicates?

Inner join will give you the records that have the same values in the joined columns between the 2 tables. From what you are saying, the 2 tables you are comparing are more or less the same, and full outer join giving you records from both tables, chances are you are going to get a lot of duplicates.

Why is my join duplicating rows?

In some cases, you need to join tables by multiple columns. In these situations, if you use only one pair of columns, it results in duplicate rows.

Why does full outer join not work?

You're getting that error because MySQL does not support (or recognize) the FULL OUTER JOIN syntax. However, it is possible emulate a FULL OUTER JOIN in MySQL. We actually need two queries. One query return all the rows from the table on the left.

How do you avoid duplicates in SQL join?

How do I prevent duplicate rows from joining multiple tables? Solution. Select column values in a specific order within rows to make rows with duplicate sets of values identical. Then you can use SELECT DISTINCT to remove duplicates.


1 Answers

MySQL doesn't have syntax keyword FULL OUTER JOIN. You have to use combination of LEFT and RIGHT JOIN to obtain full joins.

SELECT  t0.hugot_id                     as hugot_id,
        t0.upvotes                      as upvotes,
        t1.comment_count                as comment_count
FROM
    hugot_votes_stats as t0
LEFT JOIN
    hugot_comment_stats as t1
ON
    t0.hugot_id = t1.hugot_id

UNION ALL 

SELECT  t0.hugot_id                     as hugot_id,
        t0.upvotes                      as upvotes,
        t1.comment_count                as comment_count
FROM
    hugot_votes_stats as t0
RIGHT JOIN
    hugot_comment_stats as t1
ON
    t0.hugot_id = t1.hugot_id
like image 193
Mudassir Hasan Avatar answered Oct 11 '22 22:10

Mudassir Hasan