Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join different tables based on condition

create table [premiumuser] (user_id int, name nvarchar(50));
create table [liteuser] (user_id int, name nvarchar(50));
create table [feature] (id nvarchar(50), user_id int, userkey int);

insert into [premiumuser] select 1, 'stephen';
insert into [premiumuser] select 2, 'roger';

insert into [liteuser] select 1, 'apollo';
insert into [liteuser] select 2, 'venus';

insert into feature select 'Upload content', 1, 1;
insert into feature select 'Create account', 1, 0;
insert into feature select 'View content', 2, 0;

I would like to see data from feature table and instead of userid i want the username.
The catch here is if userkey is 0, get the username from liteuser table, else from premiumuser table.
Data should be like

'Upload content', 'stephen', 1
'Create account', 'apollo', 0
'View content', 'venus', 0
like image 216
Null Head Avatar asked Apr 29 '13 01:04

Null Head


People also ask

How do you join two tables based on conditions?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.

How do I join different tables in SQL?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

What are the 4 different table joining types?

There are four main types of JOINs in SQL: INNER JOIN, OUTER JOIN, CROSS JOIN, and SELF JOIN.


2 Answers

Try this:

select 
    f.id,
        case when userkey=0 then l.name else p.name end as username
from [feature] f
    left join [liteuser] l on l.user_id = f.user_id
    left join [premium user] p on p.user_id = f.user_id
like image 181
Pieter Geerkens Avatar answered Nov 22 '22 00:11

Pieter Geerkens


SELECT f.id
, (CASE WHEN f.userkey = 0 THEN l.name ELSE p.name END) AS name
, f.userkey
FROM feature f
LEFT JOIN liteuser l on f.user_id = l.user_id
LEFT JOIN premiumuser p on p.user_id = l.user_id

I suggest using left joins over inner joins, as you seem to be asking about all users associated with a given feature. This way, features with no associated users will have NULL as the name. Additionally, using two inner joins against the user tables will only return only those features which have an entry for the same user in both the premium and lite tables.

like image 20
Esoteric Screen Name Avatar answered Nov 22 '22 00:11

Esoteric Screen Name