如何连接表而不重复mysql中的列

时间:2015-10-14 05:35:36

标签: mysql join where multiple-columns

我有两张桌子:

table1(限制5):

+--------------+
| TF_ID        |
+--------------+
| T139297_1.02 | 
| T025433_1.02 | 
| T025429_1.02 | 
| T045327_1.02 | 
| T088966_1.02 | 
+--------------+

table2(限制5):

+--------------+-----------+------------+-------------+
| TF_ID        | Family_ID | TSource_ID | DBID        |
| T000001_1.02 | F001_1.02 | TS19_1.02  | FBgn0085089 |
| T000002_1.02 | F002_1.02 | TS07_1.02  | AMAG_03406  | 
| T000003_1.02 | F002_1.02 | TS07_1.02  | AMAG_05299  | 
| T000004_1.02 | F002_1.02 | TS07_1.02  | AMAG_10904  |
| T000005_1.02 | F002_1.02 | TS07_1.02  | AMAG_15258  | 
+--------------+-----------+------------+-------------+

我想通过 TF_ID 列加入这两个表格,我试过这个:

select a.TF_ID, b.TF_ID, b.Family_ID from table1 a, table2 b where a.TF_ID=b.TF_ID; 

输出如下:

+--------------+--------------+-----------+
| TF_ID        | TF_ID        | Family_ID |
+--------------+--------------+-----------+
| T014411_1.02 | T014411_1.02 | F070_1.02 | 
| T014431_1.02 | T014431_1.02 | F070_1.02 | 
| T014439_1.02 | T014439_1.02 | F070_1.02 | 
| T014447_1.02 | T014447_1.02 | F070_1.02 | 
| T014450_1.02 | T014450_1.02 | F070_1.02 |

如果我不重复 TF_ID 列,我该怎么办? 我是数据库新手,请帮忙

2 个答案:

答案 0 :(得分:1)

只需选择一次;你不必两次选择它。例如:

SELECT a.TF_ID, b.Family_ID
FROM table1 a, table2 b
WHERE a.TF_ID=b.TF_ID; 

更好的是,使用USING

SELECT a.TF_ID, b.Family_ID
FROM table1 a
    LEFT JOIN table2 b USING (TF_ID);

答案 1 :(得分:1)

选择a.TF_ID,b.Family_ID,b.TSource_ID,b.DBID 来自table1 a 左连接table2 b on a.TF_ID = b.TF_ID;