【问题标题】:Joining two tables based on column value根据列值连接两个表
【发布时间】:2021-01-14 21:01:24
【问题描述】:

如果在第一次连接时满足条件,我需要连接不同的表,因此,如果第一次连接的列的值为 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;

【问题讨论】:

标签: mysql sql join case


【解决方案1】:

case表达式返回一个值,不能用于条件执行代码。改为LEFT JOINs。

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;

【讨论】:

    【解决方案2】:

    您可以在 WHERE 子句中使用 LEFT 连接和过滤器:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 2021-05-30
      相关资源
      最近更新 更多