Chris
Chris

Reputation: 3846

MySQL: query depending on field value - can CASE help build your query?

To make it easy, there are table1 (id, field1, other_table_id), table2 (id, field1) and table3 (id, field1). I have a SELECT on table1 but depending if the value of field1 = 2 or 3, it should JOIN with table 2 or 3... (the other_table_id is then either the id of table2 or table3).

Can I use CASE for that? If not, how can I do it best? Can I do it in one query?

Thank you very much in advance!


PS: I think this is a similar topic: MySQL query where JOIN depends on CASE but I did not understand the solution. Also, I don't get how to use CASE from MySQL (http://dev.mysql.com/doc/refman/5.0/en/case-statement.html)...


EDIT: Thank you for your answer, ypercube! I am sorry, I described the structure not completely right. Actually, the tables look like this:

table1: id, assigned_to, assigned_id rooms_assigned: id, objects_id, room_type_id objects: id, ...

So, I have the object id in PHP $object_id, so how do you use this in the WHERE in the query?

According to your answer, would the right query look like this then?:

SELECT COALESCE (ra.objects_id, o.id) AS objects_id
FROM table1 as t
LEFT JOIN rooms_assigned AS ra
ON (ra.id,2)=(t.assigned_id,t.assigned_to)
LEFT JOIN objects AS o ON (o.id,3)=(t.assigned_id,t.assigned_to)

WHERE ?

EDIT 2: I think I solved the question about the "WHERE" for myself. I simply did not use WHERE in the query statement, but added it to both "ONs", like ON (ra.id,ra.object_id,2) = (t.assigned_id,".$object_id.",t.assigned_to)...

Thank you again, you were a great help! :)

Upvotes: 0

Views: 159

Answers (1)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115630

Use two LEFT joins and COALESCE() in the SELECT list:

SELECT
    COALESCE(t2.someColumn, t3.someColumn) AS someColumn

FROM
      table1 AS t
  LEFT JOIN
      table2  AS t2
          ON (t2.id, 2) = (t.other_table_id, t.field1)
  LEFT JOIN
      table3  AS t3
          ON (t3.id, 3) = (t.other_table_id, t.field1)

Upvotes: 1

Related Questions