I want to get some results via query simillar to:
SELECT * FROM users LEFT JOIN IF (users.type = '1', 'private','company') AS details ON users.id = details.user_id WHERE users.id = 1
Any ideas?
One way to do a “Conditional Join” in MySQL is by using a “LEFT JOIN”. Create a “LEFT JOIN” for each condition and combine the results into one column using an “IF” statement by the “SELECT” expression.
You can not use the IF THEN ELSE END IF -stuff in a SELECT in this way. However, you can use it in stored procedures and functions. I would JOIN u.id with both m.
Always put the join conditions in the ON clause if you are doing an INNER JOIN . So, do not add any WHERE conditions to the ON clause, put them in the WHERE clause. If you are doing a LEFT JOIN , add any WHERE conditions to the ON clause for the table in the right side of the join.
I'm sure this is already resolved, but for people with a similar problem.
You can use multiple left joins to get the data from both tables, then use an IF() to determine which of the column(s) you want as your result.
SELECT *, IF (users.type = 1, p.name, c.name) AS name FROM users LEFT JOIN private AS p ON (users.type = 1 AND users.id = p.user_id) LEFT JOIN company AS c ON (users.type != 1 AND users.id = c.user_id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With