使用mySql连接单行的多列

时间:2015-07-08 12:04:07

标签: mysql database mysqli

I have a query which results in single row like: (table_1)

        | col_1 | col_2 | col_3 |
row->1  | A     | B     | C     |

另一个查询产生两行,如:(table_2)

        | col_1 | col_2 |
row->1  | A     | X     |
row->2  | A     | Y     |

两个表的公共值是col_1(A)。我需要的是:

|   col_1   |   col_2   |   col_3   |   col_4   |   col_5   |
|   A       |   B       |   C       |   X       |   Y       |

请提供最简单的方法来实现这一点。

1 个答案:

答案 0 :(得分:0)

你可以试试 -

SELECT a.col_1,a.col_2,a.col_3, 
(SELECT b.col_2 FROM table2 AS b WHERE b.col_1=a.col_1 LIMIT 1) as col_4, 
(SELECT b.col_2 FROM table2 AS b WHERE b.col_1=a.col_1 LIMIT 1,1) as col_5 
FROM table1;