仅两个表之间的多个连接

时间:2015-02-23 18:33:32

标签: mysql database join

表1:key_item#,code_1,code_2,code_3

表2:uniq_code,code_desc

表1:

key_item#  code_1  code_2  code_3
   1         Y01    M02     X01
   2         Y01    M04     X01

表2:

uniq_code      code_desc
   Y01       DescriptionY01
   M02       DescriptionM02
   X01       DescriptionX01
   M04       DescriptionM04

更好的图片细节https://dl.dropboxusercontent.com/u/9951225/Untitled-4.jpg

查询结果

key_item#   code_1     code_desc      code_2        code_desc    cod_3    code_desc
   1          Y01    DescriptionY01     M02     DescriptionM02    X01   DescriptionX01
   2          Y01    DescriptionY01     M04     DescriptionM04    X01   DescriptionX01

查询

SELECT     Table1.key_item#,
           Table1.code_1,
           Table2.code_desc,
           Table1.code_2,
           Table2.code_desc, 
           imc_iamerican_claim_lines.Add_diagnosis1 

FROM       msp_dx9_priority.dx09code_matrix 
INNER JOIN Table1 ON Table1.code_1 = Table2.uniq_code 
INNER JOIN Table1 ON Table1.code_2 = Table2.uniq_code

我无法查看“Not unique table Alias”错误

2 个答案:

答案 0 :(得分:1)

您需要为联接设置别名,以便查询引擎知道如何消除第二个Table1中第一个Table1的歧义。这里的文档:http://dev.mysql.com/doc/refman/5.0/en/join.html

以下是一个例子:

SELECT     Table1.key_item#, -- which join should this come from? code1 or code2?
           t1_code1.code_1,
           Table2.code_desc, -- don't know what is Table2, perhaps t1_code1?
           t1_code2.code_2,
           Table2.code_desc, -- don't know what is Table2, perhaps t1_code2?
           imc_iamerican_claim_lines.Add_diagnosis1  -- also don't know what this is :)

FROM       msp_dx9_priority.dx09code_matrix 
INNER JOIN Table1 t1_code1 ON t1_code1.code_1 = Table2.uniq_code 
INNER JOIN Table1 t1_code2 ON t1_code2.code_2 = Table2.uniq_code

答案 1 :(得分:0)

我发现了这种方法



SELECT t1.key, t1.code_1, t21.`desc` as desc_1, t1.code_2, t22.`desc` as desc2, t1.code_3, t23.`desc` as desc3 FROM t1
LEFT JOIN t2 t21 on t1.code_1 = t21.code
LEFT JOIN t2 t22 ON t1.code_2 = t22.code
LEFT JOIN t2 t23 ON t1.code_3 = t23.code;




通过这个参考,我做了我的最终报告。以防万一有人需要它。