如何组合两个具有两个值的表来连接

时间:2016-12-09 01:22:41

标签: mysql join

我有这两张桌子

tbl_Output

    ref_id1 | desc1 | rec_type
       1     value1      1     
       1     value2      2  



tbl_Output2

    ref_id2 | desc2 | rec_type
        1      value3     1
        1      value4     2

我如何加入这两张桌子?显示

ref_id1 | desc1  | ref_id2 | desc2  | rec_type
   1      value1      1      value3      1
   1      value2      1      value4      2

而不是

ref_id1 | desc1  | ref_id2 | desc2  | rec_type
   1      value1      1      value3      1
   1      value2      1      value4      2
   1      value1      1      value3      1
   1      value2      1      value4      2

Here is my Query:
SELECT *
  FROM tbl_Output1 as O
  inner JOIN tbl_Output2 as O2 on
  O.ref_id1 = O2.ref_id2

注意:我已经使用了不同种类的连接。

2 个答案:

答案 0 :(得分:1)

尝试加入 id1 / id2 rec_type列:

SELECT t1.ref_id1,
       t1.desc1,
       t2.ref_id2,
       t2.desc2,
       t1.rec_type
FROM tbl_Output t1
INNER JOIN tbl_Output2 t2
    ON t1.ref_id1 = t2.ref_id2 AND
       t1.rec_type = t2.rec_type

在这里演示:

SQLFiddle

答案 1 :(得分:1)

这可能是最简单的方法:

SELECT o1.ref_id1,o1.desc1,o2.ref_id2,o2.desc2,rec_type FROM tbl_Output1 o1
  INNER JOIN tbl_Output2 o2 USING(rec_type);

这是SQL Fiddle