Mysql - 如何在左连接中为整个表数据添加别名

时间:2015-10-17 08:47:25

标签: mysql sql alias foreign-key-relationship

假设我有两张桌子,
users(id, name, gender)
posts(id, user_id(foreign_key from users), body, date)

我需要查询帖子,结果应该如下所示

[
  "id": 1,
  "body": "Some post body",
  "date": "24-10-2015"
  "user": [
   "id": 23,
   "name": "FirstName LastName",
   "gender": "male"
  ]
 ]

我试过这个,它给出了两个表的所有属性。但我需要users表中的属性作为数组。我怎么能这样做?

SELECT * 
  FROM  `posts` 
  LEFT 
  JOIN  `users` 
  ON  `posts`.`user_id` =  `users`.`id` 

2 个答案:

答案 0 :(得分:1)

您可以使用group_concat功能。此函数以逗号分隔的形式生成用户数据。我对你的数据库表并不太了解,但我试着设置一个前 -

SELECT post.Id, group_concat(users.id) as user_id, group_concat(users.name) as user_name, group_concat(users.gender) as user_genders
FROM  `posts` 
LEFT  JOIN  `users` 
ON  `posts`.`user_id` =  `users`.`id` 
GROUP BY posts.id

答案 1 :(得分:1)

试过这个。 http://sqlfiddle.com/#!9/a907b/21

您可以进一步格式化。

SELECT CONCAT('[\n "id": ',POSTS.ID,', \n "body": "'
  ,BODY,'",\n  "date": "' ,DATE,'"\n  "user": [\n   "id": '
  ,USERS.ID,',\n   "name": "', NAME,'",\n   "gender": "'
  ,gender,'"\n  ]\n ]')
FROM USERS
LEFT JOIN POSTS ON users.id=posts.user_id

要在sqlfiddle中查看,请使用Run SQL按钮上的下拉菜单,然后选择plaintext output