我有这些MySQL表:
表A:
id t_id type
--------------
1 1 0
2 2 0
3 3 0
4 4 0
5 5 0
6 1 1
7 2 1
8 3 1
9 4 1
10 5 1
11 1 2
12 2 2
13 3 2
14 4 2
15 5 2
表B:
id b
-------
1 ba
2 bb
3 bc
4 bd
5 be
表C:
id c
-------
1 ca
2 cb
3 cc
4 cd
5 ce
表D:
id d
-------
1 da
2 db
3 dc
4 dd
5 de
表A中的类型字段引用另一个表:
0 -> B
1 -> C
2 -> D
t_id是指特定表中的id
现在我正在寻找一个给我这个结果的查询:
id type t_id b c d
---------------------------------
1 0 1 ba - -
2 0 2 bb - -
3 0 3 bc - -
4 0 4 bd - -
5 0 5 be - -
6 1 1 - ca -
7 1 2 - cb -
8 1 3 - cc -
9 1 4 - cd -
10 1 5 - ce -
11 2 1 - - da
12 2 2 - - db
13 2 3 - - dc
14 2 4 - - dd
15 2 5 - - de
- should be an empty field.
这可能在MySQL吗?
答案 0 :(得分:2)
SELECT A.id, A.type, A.t_id, B.b, NULL AS c, NULL AS d
FROM A JOIN B ON A.t_id = b.id
WHERE A.type = 0
UNION ALL
SELECT A.id, A.type, A.t_id, NULL, C.c, NULL
FROM A JOIN C ON A.t_id = c.id
WHERE A.type = 1
UNION ALL
SELECT A.id, A.type, A.t_id, NULL, NULL, D.d
FROM A JOIN D ON A.t_id = d.id
WHERE A.type = 2;
答案 1 :(得分:2)
另一种替代解决方案是使用LEFT JOIN
SELECT a.*,
CASE WHEN a.type = 0 THEN b.b ELSE NULL END b,
CASE WHEN a.type = 1 THEN c.c ELSE NULL END c,
CASE WHEN a.type = 2 THEN d.d ELSE NULL END d
FROM tableA a
LEFT JOIN tableB b
ON a.t_id = b.id
LEFT JOIN tableC c
ON a.t_id = c.id
LEFT JOIN tableD d
ON a.t_ID = d.id