Eric E
Eric E

Reputation: 592

Rename returned values from SQL Join Query

Lets say we have the following query

SELECT b.user_name, c.user_name, msg 
FROM user_messages a
JOIN users b ON b.user_id = a.user_from 
JOIN users c ON c.user_id = a.user_to 
WHERE a.user_from = 'ds4EpcrmUt' 
OR a.user_to = 'ds4EpcrmUt'

When querying this from NodeJS I will only receive one of the user_names because both returned values have the same name.

Is there some way to rename their returned values like the following?

b.user_name = user_from
c.user_name = user_to

Upvotes: 1

Views: 54

Answers (3)

Rahul kumar
Rahul kumar

Reputation: 116

SELECT b.user_name as user_from, c.user_name as user_to, msg 
FROM user_messages a
JOIN users b ON b.user_id = a.user_from 
JOIN users c ON c.user_id = a.user_to 
WHERE a.user_from = 'ds4EpcrmUt' 
OR a.user_to = 'ds4EpcrmUt'

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133400

When you refere to same column name you need different column alias name eg user_name1 and user_name1 or the column name alias you prefer :

SELECT b.user_name user_name1, c.user_name user_name2, msg 
FROM user_messages a
JOIN users b ON b.user_id = a.user_from 
JOIN users c ON c.user_id = a.user_to 
WHERE a.user_from = 'ds4EpcrmUt' 
OR a.user_to = 'ds4EpcrmUt'

Upvotes: 1

Fahmi
Fahmi

Reputation: 37493

Try below -

SELECT b.user_name as user_from, c.user_name as user_to, msg 
FROM user_messages a
JOIN users b ON b.user_id = a.user_from 
JOIN users c ON c.user_id = a.user_to 
WHERE a.user_from = 'ds4EpcrmUt' 
OR a.user_to = 'ds4EpcrmUt'

Upvotes: 2

Related Questions