Reputation: 2896
I am failing to understand the behavior of conditional join. Here is a comment table where there are two types of users. if the user_type_id=1 then the data should come from admins table, if the user_type_id=2 then the data should come from users table.
So I wrote the query as follows:
select a.name as admin_name, concat(u.first_name, ' ', u.last_name) as user_name, ptc.*
from project_task_comments ptc
left join admins a on a.id= ptc.user_id and ptc.user_type_id=1
left join users u on u.id=ptc.user_id and ptc.user_type_id=2
and ptc.id=1
And Here is the result:
my question is why (in the result set) the row 3 and 5 has admin_name and user_name is null? Am I missing something?
admins table:
+----+----------------+
| id | name |
+----+----------------+
| 1 | ADMIN John Doe |
+----+----------------+
users table:
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | User | Alice |
+----+------------+-----------+
Upvotes: 0
Views: 99
Reputation: 116
As per your data, there're three records for "ptc.user_type_id=2", 1. ptc.id = 1 2. ptc.id = 3 3. ptc.id = 5 In your query you've already mentioned to put records which belongs to the first instance (i.e. ptc.id = 1). So if you wants all three then you need to use the following query.
SELECT a.name as admin_name, concat(u.first_name, ' ', u.last_name) as user_name, ptc.*
FROM project_task_comments ptc
left join admins a on a.id= ptc.user_id and ptc.user_type_id=1
left join users u on u.id=ptc.user_id and ptc.user_type_id=2
Upvotes: 2
Reputation: 8701
Generally speaking, you need to SELECT the main table (e.g. users) and do TWO conditional joins of the related tables.
This will generally mean that internally, your query will return an array of rows in the following manner: comment.* | user.* | admin.*
For some rows, you will have null columns for the user columns, for other rows you will have null columns for the admin columns. In the end, you will probably need the first non-null value.
So if you have a row such as:
comment.id | comment.text | user.username | admin.username
123 | "Example text" | null | john2019
In the end you want to escape the null
and return just the john2019
.
The MySQL function COALESCE() comes to aid:
SELECT comment.id, comment.text, COALESCE(user.username, admin.username)
It will select the first, non-null column from the provided ones, so the row selected will be:
123 | "Example text" | john2019
I hope you find this not too confusing. Let me know in a comment below if you need further clarification.
Upvotes: 1