gpt4 book ai didi

基于 IF 条件的两个表之一的 MySQL JOIN

转载 作者:行者123 更新时间:2023-11-29 02:13:32 25 4
gpt4 key购买 nike

SELECT Table1.Filter, Table1.Condition, Combined.Data FROM Table1
LEFT JOIN
(SELECT Key, Data FROM IF(Table1.Filter, Table2, Table3))) AS Combined
ON Table1.Condition = Combined.Key

我想创建一个 MySQL View ,显示 Table1 的所有列,以及 Table2Table3 的列,具体取决于字段在 Table1.Filter 上。

一个简单的解决方案是 LEFT JOIN Table2Table3,在列上使用 NULL不适用。有没有办法避免创建 2 列?我不能 UNION Table2Table3 因为它们可能包含相同的 Key

最佳答案

下面应该做你想做的:

SELECT t1.Filter, t1.Condition,
COALESCE(t2.Data, t3.Data) as Data
FROM Table1 t1 LEFT JOIN
Table2 t2
ON t1.Filter AND t2.Key = t1.Condition LEFT JOIN
Table3 t3
ON (NOT t1.Filter) AND t3.key = t1.condition;

您不能让条件选择 FROM 中的表。但是,您可以在 ON 条件中设置条件。

关于基于 IF 条件的两个表之一的 MySQL JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45156459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com