Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 基于列值联接两个表_Mysql_Sql_Join_Case - Fatal编程技术网

Mysql 基于列值联接两个表

Mysql 基于列值联接两个表,mysql,sql,join,case,Mysql,Sql,Join,Case,如果条件在第一次连接时满足,我需要连接不同的表,因此,如果第一次连接的一列的值为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

如果条件在第一次连接时满足,我需要连接不同的表,因此,如果第一次连接的一列的值为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
表达式返回一个值,不能用于有条件地执行代码。改为左连接

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;

您可以在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);
请注意,所有列都应使用相应的表名/别名进行限定。

请查看:欢迎使用SO。请参阅: