我在本地服务器上用phpMyAdmin创建了一个mySQL数据库。在这个数据库中,我存储了我的朋友的名字和最喜欢的NBA球队。这显然是一个多对多的关系。因此,我在MySQL中运行以下脚本为该数据库创建适当的表:
CREATE TABLE `friends` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `teams` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `relations` (
`friends_id` int(4) NOT NULL,
`teams_id` int(4) NOT NULL,
`status` varchar(30) NOT NULL
);
显然,我在这些表中插入了一些值,但是我没有提供大量的源代码,以节省一些空间。其中一小部分如下:
INSERT INTO `friends` (`id`, `name`)
VALUES
(1,'David Belton'),
(2,'Alex James');
INSERT INTO `teams` (`id`, `name`)
VALUES
(1,'Cleveland Cavaliers'),
(2,'Boston Celtics'),
(3,'Houston Rockets');
INSERT INTO `relations` (`friends_id`, `teams_id`, `status`)
VALUES
(1,1, 'Current'),
(2,1, 'Current'),
(2,2, 'Past'),
(2,3, 'Past');
在运行从数据库中获取数据并打印它们的PHP脚本之后,我希望为每个朋友提供以下类型的有效json输出:
{
"id": "1",
"name": "Alex James",
"Current team": ["Boston Celtics"]
"Past team": [ "Cleveland Cavaliers", "Houston Rockets"]
}
如何为每个拥有MySQL的人制作这个最喜欢的球队?
P.S。我目前的问题的灵感来自以下已回答的问题:How to join arrays with MySQL from 3 tables of many-to-many relationship
答案 0 :(得分:1)
SELECT
CONCAT(
"{"
, '"id"' , ":" , '"' , friends.id , '"' , ","
, '"name"' , ":" , '"' , friends.name , '"' , ","
,
CASE
WHEN relations.status = 'Current'
THEN CONCAT('"CurrentTeam":["', teams.name ,'"]')
ELSE CONCAT('"pastTeam": ' , '[' , GROUP_CONCAT( '"',teams.name, '"'),']' )
END
, "}"
)
AS json
FROM
friends
INNER JOIN
relations
ON
friends.id = relations.friends_id
INNER JOIN
teams
ON
relations.teams_id = teams.id
group by friends.id,relations.status
答案 1 :(得分:0)
对于这些类型的查询,你必须使用mysql版本5.7使用这些你可以使用json类型&查询中的函数..
答案:
SELECT GROUP_CONCAT( JSON_OBJECT(
'id', f.id, 'fname', f.name, 'tname', t.name, 'current_status', r.status), (SELECT JSON_OBJECT('name', tm.name)
FROM teams tm, relations re
WHERE tm.id = re.teams_id
AND f.id = re.friends_id
AND re.status = "Past"))
FROM teams t, relations r, friends f
WHERE t.id = r.teams_id
AND f.id = r.friends_id
AND r.status = "Current"