从MYSQL连接查询中获取元素列表

时间:2017-01-24 20:44:31

标签: mysql

我想要的结果是:

  

“ID”:1,   “技能”:[{“skill_name”:“产品   设计 “},{” skill_name “:” 图形   设计“}]

我的结果是:

  

{“id”:1,“技能”:“产品设计”},{“id”:1,“技能”:“平面设计”}

我的查询是:

select `u`.`id`, `s`.`skill_name` as `skills`
from `users` as `u`
    left join `user_skills` as `s` on `u`.`id` = `s`.`user_id` 
where `u`.`id` = 1

我尝试过GROUP BY user.id或SELECT DISTINCT,但没有运气。

如何为每个id获取多个结果的数组?

1 个答案:

答案 0 :(得分:1)

SELECT u.id, group_concat(s.skill_name) AS skills
FROM users AS u
LEFT JOIN user_skills AS s ON u.id = s.user_id
WHERE u.id = 1
GROUP BY u.id

输出将是:

id skills
-- ------------------------------
1  Product Design, Graphic Design

如果您真的想要以下列格式输出:

  

{“id”:1,“技能”:[{“skill_name”:“产品设计”},{“skill_name”:“平面设计”}}}

然后尝试这个SQL - (疯狂版):

SELECT 
  '{"id":', u.id, ', skills:[', 
  group_concat(concat('{"skill_name":"', s.skill_name, '"}')) AS skills,
  ']}'
FROM users AS u
LEFT JOIN user_skills AS s ON u.id = s.user_id
WHERE u.id = 1
GROUP BY u.id

SELECT concat('{“id”:',id,',技能:['),group_concat(concat('{“skill_name”:“',skill_name,'”}'))AS技能,'] “