Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Join and show results if join false

Tags:

sql

mysql

I have a table - comments. Users can post if not a member of the site but want to show their details if they are.

So if a user comments who is NOT a member I show their posts but don't link to their profile, because they don't have one.

So, in the following query I want to return the rows even if there is no join:

select wc.comment, wc.comment_by_name, wc.user_id, u.url from comments wc
join users u on wc.wag_uid = u.user_id
where id = '1237' group by wc.comment order by wc.dateadded desc

I want to return:

comment    comment_by_name    user_id    url
-------    ---------------    -------    ----
hello      dan                12         /dan
hey        jane                          /jane
world      jack               10         /jack

But the above does not return the data for jane as she does not have a user_id

Is there a way to return all data even if the join is null?

like image 773
StudioTime Avatar asked Nov 24 '12 07:11

StudioTime


People also ask

Can we use != IN join?

Such joins are called non-equi JOINs, and they are also possible in SQL. When you join two tables using other conditional operators, beyond the equal sign, non-equi JOINs come into play. Comparison operators, like <, >, <=, >=, != , and <> and the BETWEEN operator work perfectly for joining tables in SQL.

Which join return rows that don't match?

The JOIN or INNER JOIN does not return any non-matching rows at all. It returns only the rows that match in both of the tables you join. If you want to get any unmatched rows, you shouldn't use it. The LEFT JOIN and the RIGHT JOIN get you both matched and unmatched rows.

What is conditional join?

Using conditional JOIN syntax, you can establish joins based on conditions other than equality between fields. In addition, the host and cross-referenced join fields do not have to contain matching formats, and the cross-referenced field does not have to be indexed.

Which join is used to display unmatched records?

Outer joins are joins that return matched values and unmatched values from either or both tables.


1 Answers

use LEFT JOIN instead

SELECT  wc.comment, wc.comment_by_name, wc.user_id, u.url 
FROM    comments wc
        LEFT JOIN users u 
           on wc.wag_uid = u.user_id
WHERE id = '1237' 
GROUP BY wc.comment 
ORDER BY wc.dateadded DESC

basically INNER JOIN only select records which a record from one table has atleast one match on the other table while LEFT JOIN select all rows from the left hand side table (in your case, it's comments) whether it has no match on the other table.

like image 115
John Woo Avatar answered Nov 09 '22 02:11

John Woo