I have a prepared query in two versions, the first one works but the second using CASE WHEN doesn’t :
SELECT mFrom.user_name AS sender_name, mp.message AS message
FROM msg_pv mp
INNER JOIN membresmvc AS mFrom
ON mp.id_from = mFrom.id
WHERE mp.id_to = :id_member
CASE WHEN version :
SELECT mFrom.user_name AS sender_name, mp.message AS message
FROM msg_pv mp
INNER JOIN
CASE mp.from_type
WHEN "mb" THEN membresmvc AS mFrom ON mFrom.id = mp.id_from
END -- also tried "END CASE"
WHERE mp.id_to = :id_member
The value of mp.from_type is always “mb” in the msg_pv table. I exactly use the structure recommented in the MySQL reference manual. I don’t understand why the second query doesn’t work.
If your CASE espression value always evaluates to true, there is no need to have that statement.
However, I think the usage of the CASE in your query is wrong. It should be something like as shown below. You can have the CASE on the ON condition but not on the JOIN itself. This way you can join to different columns based on a condition.
This is syntactically correct but not sure what the output would be.
You can validate this statement using this link: Instant SQL Formatter
Query:
UPDATE
If you need to join to multiple tables based on a condition, then you need to make use of
LEFT OUTER JOIN. You query might look something like this assuming your second table is *second_table* and another value is “another value”EXAMPLE
Here is an example that illustrates it. This script was tested in SQL Server 2012 database. It might differ in MySQL. However, the concept of LEFT OUTER JOIN used here is same even in MySQL.
table1,table2andtable3constantin table1 has the value t2.constantin table1 has the value t3.Hope that gives you an idea to join the tables as per your requirements.
Script:
Output: