繁体   English   中英

根据列值连接两个表

[英]Joining two tables based on column value

如果第一个连接满足条件,我需要连接不同的表,因此,如果第一个连接的列的值为 1,则与一个表进行连接,但如果值为 2,则与另一个表进行连接,像这样,但 MySQL 给出错误

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;

case表达式返回一个值,不能用于代码的条件执行。 LEFT JOIN代替。

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;

您可以使用 LEFT 连接并在 WHERE 子句中进行过滤:

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);

请注意,所有列都应使用相应的表名/别名进行限定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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