在MySQL中,我希望SELECT A.* FROM A
满足内部联接条件,无论是直接(通过表B
)还是通过另一个联接表(C
),WHERE B.field = myvalue
。任何人都可以指出获得结果的正确方法吗?
我有以下表格:A,B,C,它们如下关联(A连接B,B连接C,A连接C):
B
/ \
A --- C
它看起来非常简单,但是当我运行以下代码时,我得到一个空集,即使我在将搜索限制为仅通过C加入B时得到结果:
SELECT A.* FROM A
INNER JOIN C ON C.id = A.c_id
INNER JOIN B AS B_thru_C ON B_thru_C.id = C.b_id
INNER JOIN B AS B_from_A ON B_from_A.id = A.b_id
WHERE B_thru_C.field = 'myvalue' OR B_from_A.field = 'myvalue';
# yields an empty set
SELECT A.* FROM A
INNER JOIN C ON C.id = A.c_id
INNER JOIN B AS B_thru_C ON B_thru_C.id = C.b_id
WHERE B_thru_C.field = 'myvalue';
# yields results
答案 0 :(得分:0)
这个怎么样?
SELECT A.* FROM A
LEFT OUTER JOIN C ON C.id = A.c_id
INNER JOIN B ON B.id = A.b_id OR B.id = C.b_id
WHERE B.field = 'myvalue';