我有两个表,A和B.如果表B中存在记录(按ID检查),那么我想从该表中获取此记录(表B)。如果表B中不存在,那么我想从表A中获取此记录(因此最重要的是从表B获取,但如果不存在,则从表A获取)。
之后,我希望将这些记录(来自表A或表B)与表C(来自表A或表B)连接起来。是否可以在一个查询中执行此操作?
示例:
表C:
|ID|STATUS|
|1 |4 |
表A:
|ID|SOME_VALUE|
|1 |1 |
表B:
|ID|SOME_VALUE|
|1 |1 |
现在,当我想得到ID = 1的记录时,查询应该检查表B中是否存在该ID(在我的例子中,表B中存在记录ID = 1)。 我们知道这个记录在表B中,所以我们应该将表B(记录ID = 1)与表状态连接起来,记录ID = 1。
SELECT a.*, c.* FROM `table_A` a LEFT JOIN `table_C` ON a.id = c.id WHERE c.id = 1;
但我不知道如何添加到此查询中检查表B中是否存在此记录(如果存在,则从表B获取,如果不存在,则从表A获取)。
答案 0 :(得分:2)
如果您在表A
中始终有值,则应执行此操作:
SELECT t.id, C.status FROM (
SELECT
A.id, coalesce(B.some_value, A.some_value) as some_value
FROM
A
LEFT JOIN B ON B.id = A.id
) t
INNER JOIN C on C.id = t.some_value;
这是一个小提琴:http://sqlfiddle.com/#!9/1762f35/4
P.S。我不确定我的数据模型是否正确,但
<强> UPD:强>
如果您需要按id
加入,而不是some_value
加入,这是另一个小提琴(它的方法相同):http://sqlfiddle.com/#!9/f2be17/1
答案 1 :(得分:1)
这是一种方式:
SELECT ID, SOME_VALUE, t2.STATUS
FROM (
-- Get record from B. If record exists in B then next query
-- doesn't return the record.
SELECT ID, SOME_VALUE
FROM B
WHERE ID = 1
UNION ALL
-- Get record from A. The query returns nothing if the record exists
-- in B.
SELECT ID, SOME_VALUE
FROM A
WHERE ID = 1 AND NOT EXISTS (SELECT 1 FROM B WHERE ID = 1)
) AS t1
INNER JOIN C AS t2 ON t1.ID = t2.ID
修改:上述查询的通用版本为:
SELECT ID, SOME_VALUE, t2.STATUS
FROM (
-- Get record from B. If record exists in B next query returns nothing.
SELECT ID, SOME_VALUE
FROM B
UNION ALL
-- If record doesn't exist in B previous query returns nothing
SELECT ID, SOME_VALUE
FROM A
WHERE NOT EXISTS (SELECT 1 FROM B WHERE B.ID = A.ID)
) AS t1
INNER JOIN C AS t2 ON t1.ID = t2.ID