mysql多对多数组_php – 如何使用3个多对多关系表从MySQL连接数组

“eazy”方法是使用CONCAT生成JSON.

并使用GROUP_CONCAT将多个团队记录合并为一个JSON数组.

此方法也适用于不支持创建JSON函数的旧MySQL版本.

询问

SELECT

CONCAT(

"{"

, '"id"' , ":" , '"' , friends.id , '"' , ","

, '"name"' , ":" , '"' , friends.name , '"' , ","

, '"team"' , ":" , "["

, GROUP_CONCAT('"', teams.name, '"')

, "]"

, "}"

) AS json

FROM

friends

INNER JOIN

relations

ON

friends.id = relations.friends_id

INNER JOIN

teams

ON

relations.teams_id = teams.id

WHERE

friends.id = 1

结果

| json |

|-----------------------------------------------------------------|

| {"id":"1","name":"David Belton","team":["Cleveland Cavaliers"]} |

演示

编辑了更多的朋友

询问

SELECT

CONCAT(

"["

, GROUP_CONCAT(json_records.json) # combine json records into a string

, "]"

) AS json

FROM (

SELECT

CONCAT(

"{"

, '"id"' , ":" , '"' , friends.id , '"' , ","

, '"name"' , ":" , '"' , friends.name , '"' , ","

, '"team"' , ":" , "["

, GROUP_CONCAT('"', teams.name, '"')

, "]"

, "}"

) AS json

FROM

friends

INNER JOIN

relations

ON

friends.id = relations.friends_id

INNER JOIN

teams

ON

relations.teams_id = teams.id

WHERE

friends.id IN(SELECT id FROM friends) #select the friends you need or just simply friends.id IN(1, 2)

GROUP BY

friends.id

)

AS json_records

结果

| json |

|--------------------------------------------------------------------------------------------------------------------------------------------------|

| [{"id":"1","name":"David Belton","team":["Cleveland Cavaliers"]},{"id":"2","name":"Alex James","team":["Boston Celtics","Cleveland Cavaliers"]}] |

演示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值