如何解决根据列值联接两个表
如果第一次连接的条件满足,我需要连接不同的表,因此,如果第一次连接的列的值为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,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);
请注意,所有列均应使用各自的表名/别名进行限定。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。