一起显示两个mysql表的内容

时间:2014-02-08 12:18:54

标签: mysql sql

当一个表有多个匹配的行时,试图弄清楚如何显示两个mysql表的内容,例如。以便下表显示结果:

伦敦 - 哈里史密斯,奥利弗琼斯,杰克泰勒

曼彻斯特 - 查理威廉姆斯,雅各布朗

Table One                                 Table two
+-----------------------------+          +----------------------------------+
| id | branchid | store       |          | branchid | firstname | employee  |
+-----------------------------+          +----------------------------------+
| 1  | 1        | London      |          | 1        | Harry     | Smith     |
| 2  | 2        | Manchester  |          | 1        | Oliver    | Jones     |
+-----------------------------+          | 1        | Jack      | Taylor    |
                                         | 2        | Charlie   | Williams  |
                                         | 2        | Jacob     | Brown     |
                                         +----------------------------------+

非常感谢。

1 个答案:

答案 0 :(得分:0)

GROUP_CONCAT将完成这项工作,但我们首先需要CONCAT同时将名字和姓氏放在一起:

SELECT b.store, GROUP_CONCAT(CONCAT(e.firstname, ' ', e.employee)) AS Employees
FROM TableOne b INNER JOIN TableTwo e on b.branch = e.branchid
GROUP BY b.store;

SqlFiddle here

结果:

Store       Employees       
London      Harry Smith,Jack Taylor,Oliver Jones
Manchester  Jacob Brown,Charlie Williams`