0

我有 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');

--

带有解释的查询将不胜感激。

非常感谢。

4

2 回答 2

1

使用 UNION 组合每个查询的结果:

SELECT t1.idObject, t1.objectName, t2.custName, NULL Message
FROM t1 JOIN t2 ON (t1.idObject = t2.id1)
WHERE t1.objectName = "ABC"
UNION ALL
SELECT t1.idObject, t1.objectName, NULL custName, NULL Message
FROM t1 JOIN t2 ON (t1.idObject = t2.id2)
WHERE t1.objectName = "DEF"
UNION ALL
SELECT t1.idObject, t1.objectName, NULL custName, NULL Message
FROM t1 JOIN t2 ON (t1.idObject = t2.id3)
WHERE t1.objectName = "GHI"
UNION ALL
SELECT t1.idObject, t1.objectName, NULL custName, Message
FROM t1 join t3 ON (t1.idObject = t3.id4)
WHERE t1.objectName = "JKL"

你没有提到它,但我认为Message在 ABC、DEF、GHI 情况下应该为 NULL,因为 中没有这样的列t2,而custName在 JKL 情况下应该是 NULL,因为t3.

要订购结果,您需要使 UNION 成为子查询:

SELECT * FROM (
    SELECT t1.idObject, t1.objectName, t2.custName, NULL Message
    FROM t1 JOIN t2 ON (t1.idObject = t2.id1)
    WHERE t1.objectName = "ABC"
    UNION ALL
    SELECT t1.idObject, t1.objectName, t2.custName, NULL Message
    FROM t1 JOIN t2 ON (t1.idObject = t2.id2)
    WHERE t1.objectName = "DEF"
    UNION ALL
    SELECT t1.idObject, t1.objectName, t2.custName, NULL Message
    FROM t1 JOIN t2 ON (t1.idObject = t2.id3)
    WHERE t1.objectName = "GHI"
    UNION ALL
    SELECT t1.idObject, t1.objectName, NULL custName, Message
    FROM t1 join t3 ON (t1.idObject = t3.id4)
    WHERE t1.objectName = "JKL" ) x
ORDER BY idObject, custName, Message
于 2013-05-22T23:55:57.463 回答
0

SQL 背后的想法是,它允许您用 SQL 术语表达您的确切要求,例如:

SELECT
 whatever you need, including
 CASE WHEN t1.objectName in ( 'DEF' , 'GHI') 
  THEN NULL
  ELSE t2.custName
 END AS custName
FROM
 t1, t2, t3
WHERE
 (t1.objectName = 'ABC' AND t1.idObject = t2.id1) 
 OR
 (t1.objectName = 'DEF' AND t1.idObject = t2.id2)
 OR
 ...

我希望您可以将此扩展到您的所有要求。

于 2013-05-22T23:37:45.310 回答