我有 3 张桌子 t1、t2 和 t3。以下是他们的架构。
我需要加入他们并且有条件。
In t1 table, objectName can be one of 4: 'ABC', 'DEF', 'GHI', or 'JKL'.
If t1.objectName is 'ABC', I need to join t1.idObject with t2.id1.
If t1.objectName is 'DEF', I need to join t1.idObject with with t2.id2.
If t1.objectName is 'GHI', I need to join t1.idObject with t2.id3.
If t1.objectName is 'JKL', I need to join t1.idObject with t3.id4.
I need to select t1.idObject, t1.objectName, t2.custName, t4.Message.
此外,如果 t1.objectName 是“DEF”或“GHI”,我希望 custName 在选择结果中为空。
--
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));
select * from t1;
select * from t2;
select * from t3;
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');
--
带有解释的查询将不胜感激。
非常感谢。