Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL JOIN with IF conditions

Tags:

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?

like image 308
plugowski Avatar asked May 05 '10 07:05

plugowski


People also ask

How do I use an if statement in an MySQL join query?

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.

Can we use if condition in join?

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.

Can we use joins in with clause?

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.


1 Answers

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) 
like image 81
Ludo - Off the record Avatar answered Oct 29 '22 20:10

Ludo - Off the record