This is not difficult to accomplish in MySQL, once you conceptualize the what you're asking the server to do.
I have reversed the IS NOT NULL
test against t.user_id because your original case statement seemed to be backwards, joining admin when t.user_id isn't null and joining users when t.user_id is null, which seems impossible. Aside from that, here's a query that fetches the first_name and second_name by joining user when possible and joining admin otherwise. The joins are LEFT
joins because we need to return the rows from 'ticket' regardless of which table is joinable.
SELECT t.*,
COALESCE(u.first_name,a.first_name) as first_name,
COALESCE(u.second_name,a.second_name) as second_name
FROM `tickets` `t`
LEFT JOIN `users` `u` ON `t`.`user_id`=`u`.`user_id`
LEFT JOIN `adminbb` `a` ON `t`.`admin_id`=`a`.`admin_id` AND t.user_id IS NULL
WHERE `t`.`ticket_id` =1
ORDER BY `t`.`ticketText_id`
LIMIT 0,3;
The COALESCE()
function returns the leftmost non-null value from among its arguments.
The LEFT JOIN users will pick up the values from "u" if they exist and if t.user_id isn't null, and the LEFT JOIN adminbb will look for the values from "a" only if t.user_id is null.
Conditions in the ON
clause only have to be testable expressions, they don't actually have to be "about" the table you are joining. In the case of the join against adminbb, the new join condition is actually about the table on the left rather than the table on the right, but this is still quite legitimate and will still prevent the join from being attempted when it's not needed.