用于查询四个表的SQL查询

时间:2019-04-14 22:40:27

标签: mysql sql database join

我是编写SQL查询的新手,有人可以帮我编写以下条件和联接的SQL查询吗?

我有4个表,分别是T1T2T3T4

T1 have columns a1(PK), a2, a3, a4

T2 have columns b1(PK), a1(FK), b2

T3 have columns c1(PK), a1(FK)

T4 have columns d1(PK), c1(FK), d2, d3

条件:

  1. 我想在T1

  2. 时使用a4 == "xx"的所有列
  3. 如果T1.a1 == T2.a1T1.a2 == "x",则希望将b2作为新列包含在最终结果中。

    < / li>
  4. 如果T3.c1 == T4.c1T4.d2 == "y",则从d3获取价值,该价值需要加入到step4

  5. 如果T1.a1 == T3.a1T1.a2 == "z",则d3(第3步)中的值应包含在最终结果的新列

我正在尝试解决以下问题,但是我不知道如何在最终结果中将步骤3的值d3添加到b2

select T1.a1,T1.a2,T1.a3,T1.a4,T2.b2 from
T1
left join T2 on T1.a1 == T2.a1 AND T1.a2 == "x"
left join ( 
    select T3.a1,T4.d3 from T3,T4
    where T3.c1 == T4.c1 AND T4.d2 == "y") 
) joined on joined.a1 == T1.a1 and T1.a2 == "z"
where a4 == "xx";

样本数据

T1 table :

a1 |  a2 | a3 | a4 |
1  |  x  | cat| xx |
2  |  aa | hat| la |
3  |  z  | mat| xx |

T2 table : 

b1  |  b2  | a1 | 
11  |  984 | 1  | 
22  |  234 | 2  | 

T3 table : 

c1   |  a1 | 
111  |  3  | 
222  |  7  | 

T4 table : 

d1    |  d2  | d3  | c1  |
1111  |  y   | 100 | 111 |
2222  |  yy  | 200 | 333 |


Expected Result : 

a1  |  a2  | a3   | a4 | new column
1   |  x   | cat  | xx | 984 (from T2.b2)
3   |  z   | mat  | xx | 100 (from T4.d3)

请帮助我更正我的查询。感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

假设您不希望满足条件时想要 no 结果,此查询将为您提供所需的结果。它使用CASE表达式为new column选择正确的值,并使用a2的值来决定对该值使用b2还是d3WHERE子句排除了不符合您条件的行。

SELECT T1.*, 
       CASE WHEN T1.a2 = 'x' THEN T2.b2
            WHEN T1.a2 = 'z' THEN T4.d3
       END AS `new column`
FROM T1
LEFT JOIN T2 ON T2.a1 = T1.a1
LEFT JOIN T3 ON T3.a1 = T1.a1
LEFT JOIN T4 ON T4.c1 = T3.c1
WHERE a4 = 'xx' AND (a2 = 'x' OR a2 = 'z' AND d2 = 'y')
ORDER BY a1

输出:

a1  a2  a3  a4  new column
1   x   cat xx  984
3   z   mat xx  100

Demo on dbfiddle

答案 1 :(得分:1)

您可以这样写:

SELECT T1.*,
       (CASE WHEN T1.a2 = 'x'
             THEN (SELECT T2.b2
                   FROM T2
                   WHERE T2.a1 = T1.a1
                  )
             ELSE (SELECT T4.d3
                   FROM T3 JOIN
                        T4
                        ON T4.c1 = T3.c1
                   WHERE T3.a1 = T1.a1 AND T4.d2 = 'y'
                  )
        END) as new_column
FROM T1
WHERE T1.a4 = 'xx' AND T1.a2 IN ('x', 'z')
ORDER BY T1.a1;

这假设两种可能性中的每一种最多匹配一行。

如果是这样,我发现这里的逻辑可以更好地抓住您的意图。