简体   繁体   中英

Joining two tables based on column value

I need to join different tables if a condition meets on the first join, so, if a column of the first join has a value 1 then do a join with one table, but if the value has 2 then do the join with another table, something like this but MySQL give an error

SELECT col1, col2, col3,...,col8
FROM table1 AS tb1
INNER JOIN table2 AS t2 ON tb1.id = tb2.id
INNER JOIN table3 AS t3 ON tb2.id = tb3.id
CASE
    WHEN tb2.col2 = 1   THEN INNER JOIN table4 ON id = col1
    WHEN tb2.col2 = 2   THEN INNER JOIN table5 ON id = col3
    WHEN tb2.col2 = 3   THEN INNER JOIN table6 ON id = col5
END    
WHERE tb1.id = 13;

A case expression returns a value, and can't be used for conditional execution of code. Do LEFT JOIN s instead.

SELECT col1, col2, col3,...,col8
FROM table1 AS tb1
INNER JOIN table2 AS t2 ON tb1.id = tb2.id
INNER JOIN table3 AS t3 ON tb2.id = tb3.id
LEFT JOIN table4 ON id = col1 and tb2.col2 = 1
LEFT JOIN table5 ON id = col3 and tb2.col2 = 2
LEFT JOIN table6 ON id = col5 and tb2.col2 = 3
WHERE tb1.id = 13;

You can do it with LEFT joins and filter in the WHERE clause:

SELECT col1, col2, col3,...,col8
FROM table1 AS tb1
INNER JOIN table2 AS tb2 ON tb1.id = tb2.id
INNER JOIN table3 AS tb3 ON tb2.id = tb3.id
LEFT JOIN table4 ON id = col1 AND tb2.col2 = 1
LEFT JOIN table5 ON id = col3 AND tb2.col2 = 2
LEFT JOIN table6 ON id = col5 AND tb2.col2 = 3
WHERE tb1.id = 13 AND tb2.col2 IN (1, 2, 3);

Note that all columns should be qualified with the respective table name/alias.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM