Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right join even if row on second table does not exist

Tags:

sql

mysql

I want to join two tables even if there is no match on the second one.

table user:

uid | name 1     dude1 2     dude2 

table account:

uid | accountid | name 1     1           account1 

table i want:

uid  | username | accountname 1      dude1      account1 2      dude2      NULL 

the query i'm trying with:

SELECT user.uid as uid, user.name as username, account.name as accountname FROM user RIGHT JOIN account ON user.uid=accout.uid 

what i'm getting:

uid  | username | accountname 1      dude1      account1 
like image 826
coiso Avatar asked Jun 07 '13 15:06

coiso


People also ask

Can we apply joins on 2 tables which has no related data?

Yes, you can! The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can be handy for merging tables in SQL.

How do I return rows left table not found in right table?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

How can I get non matching records from two tables in SQL?

SELECT B. Accountid FROM TableB AS B LEFT JOIN TableA AS A ON A.ID = B. Accountid WHERE A.ID IS NULL; LEFT JOIN means it takes all the rows from the first table - if there are no matches on the first join condition, the result table columns for table B will be null - that's why it works.

Which join is used to take the unmatched data from 2 tables?

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


1 Answers

use Left Join instead

SELECT user.uid as uid, user.name as username, account.name as accountname FROM user LEFT JOIN account ON user.uid=accountid.uid 
like image 161
Gonzalo.- Avatar answered Oct 01 '22 02:10

Gonzalo.-