mysql内连接3表和联合

时间:2016-02-25 11:53:46

标签: mysql sql

我以前用sparql进行查询,但是我必须用mysql做这个,我真的不知道语法。 我有这三个表:

产品:

    id o
    1 p1
    2 p2

规格:

    id o
    3 sp1
    4 sp2

来源:

    id o
    1 s1
    3 s1
    2 s2
    4 s2

正如我们所见,产品和规格可以与源不同的ID连接,所以我想我必须在源>之间进行2次选择,内部连接为2;产品和来源>规范和2之间的内部联接选择:

      SELECT * FROM
        (
            SELECT pt.o as po, st.id as psID, st.o as pso 
            FROM source_test st
            inner join products_test pt on st.id = pt.id
        ) x INNER JOIN  
        (
            SELECT st2.o as spo, st1.id as spsID,st1.o as spso      
            FROM source_test st1
            inner join specification_test st2 on st1.id =st2.id
        ) y 

这给出了:

    po  psID    pso spo spsID   spso
    p1  1   s1  sp1 3   s1
    p2  2   s2  sp1 3   s1
    p1  1   s1  sp2 4   s2
    p2  2   s2  sp2 4   s2

现在我需要过滤产品(po)和具有相同来源(pso)的规范(spo),(spso)

我是以正确的方式做事,可能是延续或好的查询:

    po  spo spso
    p1  sp1 s1
    p2  sp1 s2

提前致谢。

3 个答案:

答案 0 :(得分:0)

select p.o, s.o, so.o
from products p
    left join specification s
    left join source so on p.id=s.id and p.id = so.id;

答案 1 :(得分:0)

我唯一要做的就是过滤y ON x.pso = y.spso

    SELECT * FROM
    (
        SELECT product.o as po, source.s as psID, source.o as pso FROM source
        inner join product
            on source.s = product.s
    ) x INNER JOIN  
    (
        SELECT specification.o as spo, source.s as spsID, source.o as spso FROM source
        inner join specification
            on source.s = specification.s
    ) y ON x.pso = y.spso

结果:

    po  psID    pso spo spsID   spso
    p1  1   s1  sp1 3   s1
    p2  2   s2  sp2 4   s2

答案 2 :(得分:0)

ON x.pso = y.spso添加到您的查询中:

SELECT x.po, y.spo, y.spso
FROM
(
    SELECT products_test.o as po, source_test.id as psID, source_test.o as pso FROM source_test
     inner join products_test
        on source_test.id = products_test.id
) x INNER JOIN  
(
   SELECT specification_test.o as spo, source_test.id as spsID,source_test.o as spso      
    FROM source_test
     inner join specification_test on source_test.id =specification_test.id
) y     
  ON x.pso = y.spso