I have two tables users and *activation_details*
Users table has these data. uid is primary key.
uid | user_name
______________________
1 | John Smith
2 | Mary Smith
3 | Nancy Smith
4 | Agent Smith
activation_details has these data
aid | is_activated | user_id
______________________________________
1 | 0 | 0
2 | 1 | 4
3 | 1 | 1
4 | 1 | 777
Please note that user id 777 is not in the users table.
I need the result in this format
aid | is_activated | user_name
______________________________________________
1 | 0 | 0
2 | 1 | Agent Smith
3 | 1 | John Smith
4 | 1 | 777
If user id is present in the users table then username has to be displayed, else the user_id itself has to be displayed.
I tried some thing like this
SELECT aid, is_activated, user_id, users.user_name from activation_details, users WHERE users.uid = user_id
It gives this output, which is not useful.
aid | is_activated | user_name | user_id
________________________________________________________
2 | 1 | Agent Smith | 4
3 | 1 | John Smith | 1
Is there anyway to get this output using mysql only, I can do it with multiple queries in PHP, but that is not what I am looking.
aid | is_activated | user_name
______________________________________
1 | 0 | 0
2 | 1 | Agent Smith
3 | 1 | John Smith
4 | 1 | 777
You want to use an outer join in combination with the
coalesce()function (which returns the first non-null value in the selected columns) like this:Edit: I added one more check for the
coalesce()function which will return a0for the User in case both theuser_nameanduser_idfields are null values.Testing done in mysql: