i have a table called users contained
(Table A)
Users
user_id
username
user_type[1,2]
(Table B) if user_type=1
user_id
full_name
(Table C) if user_type=2
user_id
full_name
i want to get single record set by executing single query, is that possible in PHP mysql.
Try this:
It uses the
LEFT OUTER JOIN, which means that it joins it totable_bon the given condition. However, for each row intable_a, whether it finds a matching row intable_bor not, it will return thetable_arow. If it does not find a matching row, thetable_bcolumns are just NULL. Same thing withtable_c.Then, we just select all the
table_acolumns. However, we now have twofull_namecolumns, one fromtable_band one fromtable_c. We useCOALESCEto merge them.COALESCEreturns the first non-NULLvalue.Since we know that there is either a matching row in
table_bor a matching row intable_c, it is not a problem. However, it would be a problem if somehow you allows a matching row to be found in bothtable_bandtable_c.The risk can be mitigated by adding additional
ONclause conditions to get:Still, you will need to make sure only 1 row is present for each user in
table_bandtable_c.Instead of
COALESCEyou can optionally useCASElike:or use an
IFfunction like:SELECT table_a.*, IF(user_type=1,table_b.full_name,table_c.full_name) AS full_name
…