Mysql内连接两次并在两个连接上使用WHERE

时间:2013-04-05 03:56:13

标签: mysql inner-join

在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

1 个答案:

答案 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';