我有3个表t1,t2和t3。以下是他们的模式。
我需要加入他们并确实有条件。
我需要选择t1.idObject,t1.objectName,t2.custName,t3.Message。
create table t1 (idObject int, objectName varchar(20));
create table t2 (id1 int, id2 int, id3 int, custName varchar(20));
create table t3 (id4 int, Message varchar(20));
insert into t1 values (101, 'ABC'), (102, 'DEF'), (103, 'GHI'), (104, 'JKL'), (105, 'ABC'), (106, 'DEF'), (107, 'GHI'), (108, 'JKL');
insert into t2 values (101, 102, 103, 'Val'), (105, 106, 107, 'Mil');
insert into t3 values (104, 'Message1'), (108, 'Messgage2');
select * from t1;
select * from t2;
select * from t3;
高度赞赏带有解释的查询。
非常感谢。
答案 0 :(得分:1)
你可以试试这个:
SELECT
t1.idObject,
t1.objectName,
t2.custName,
t3.Message
FROM
t1
LEFT JOIN t2
ON t1.idObject = (
CASE
WHEN t1.objectName = 'ABC' THEN t2.id1
WHEN t1.objectName = 'DEF' THEN t2.id2
WHEN t1.objectName = 'GHI' THEN t2.id3
ELSE 0
END
)
LEFT JOIN t3
ON t1.idObject = (
CASE
WHEN t1.objectName = 'JKL' THEN t3.id4
ELSE 0
END
)
答案 1 :(得分:0)
您可以通过左连接和coalesce()的组合来实现此目的。这是一般的想法。
select coalesce(t2.value, t3.value, t4.value) theValue
from table1 t1 left join table2 t2 on something
left join table2 t3 on something else
left join table2 t4 on something different
where whatever