在连接另一个表时为每个case在case语句中提供where条件,可以使用以下方法:
SELECT column1, column2,
CASE
WHEN column3 = 'value1' THEN (SELECT column4 FROM table2 WHERE condition1)
WHEN column3 = 'value2' THEN (SELECT column4 FROM table3 WHERE condition2)
ELSE (SELECT column4 FROM table4 WHERE condition3)
END AS result
FROM table1;
在上述示例中,根据column3的值,使用不同的子查询为每个case提供where条件。
SELECT column1, column2, column4
FROM table1
LEFT JOIN table2 ON table1.column3 = 'value1' AND table2.condition1
LEFT JOIN table3 ON table1.column3 = 'value2' AND table3.condition2
LEFT JOIN table4 ON table1.column3 NOT IN ('value1', 'value2') AND table4.condition3;
在上述示例中,根据column3的值和连接条件,使用不同的连接来为每个case提供where条件。
CREATE TEMPORARY TABLE temp_table (condition_column INT);
INSERT INTO temp_table
SELECT CASE
WHEN column3 = 'value1' THEN (SELECT condition1 FROM table2 WHERE condition1)
WHEN column3 = 'value2' THEN (SELECT condition2 FROM table3 WHERE condition2)
ELSE (SELECT condition3 FROM table4 WHERE condition3)
END AS condition
FROM table1;
SELECT column1, column2,
CASE
WHEN column3 = 'value1' THEN (SELECT column4 FROM table2 WHERE condition1 = (SELECT condition_column FROM temp_table))
WHEN column3 = 'value2' THEN (SELECT column4 FROM table3 WHERE condition2 = (SELECT condition_column FROM temp_table))
ELSE (SELECT column4 FROM table4 WHERE condition3 = (SELECT condition_column FROM temp_table))
END AS result
FROM table1;
在上述示例中,首先创建一个临时表temp_table来存储每个case的where条件。然后,在case语句中引用临时表,并根据条件从相应的表中获取数据。
请注意,以上示例中的表名、列名和条件仅作为示例提供,实际使用时需要根据具体情况进行修改。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云