如何使用mysql将一个表中的所有列集成到另一个表的一列中

时间:2017-06-14 15:47:34

标签: mysql database

表1:员工

name| mobile| location
alex| 123   | australia
john| 456   | paris
kohl| 678   | australia

表2:就业

id|location |data
1 |australia|[{"name":"alex","mobile":"123"},{"name":"kohl","mobile":"678"}]
2 |paris    |[{"name":"john","mobile":"456"}]

我有两张名为" employee"和"就业"。如何将employee表的所有列值都放入一个就业表的列中,如表2所示。我是SQL查询的新手。老实说,我对如何继续不知道。任何指针和建议都表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以使用CONCATGROUP_CONCAT使用以下解决方案来获得此结果:

SELECT location, CONCAT("[", GROUP_CONCAT(CONCAT('{"name":"', name, '","mobile":"', mobile, '"}')), "]") AS data
FROM employee
GROUP BY location
  

演示: http://sqlfiddle.com/#!9/ab25ee/2/0

使用JOIN employeeemployment表,您可以使用以下解决方案:

SELECT employment.id, employment.location, CONCAT("[", GROUP_CONCAT(CONCAT('{"name":"', name, '","mobile":"', mobile, '"}')), "]") AS data 
FROM employment INNER JOIN employee ON employment.location = employee.location 
GROUP BY id, location
  

演示: http://sqlfiddle.com/#!9/12f9c9/1/0