php - 如何从 3 个多对多关系表中将数组与 MySQL 连接

标签 php mysql json

我在本地服务器上使用 phpMyAdmin 创建了一个 mySQL 数据库。在这个数据库中,我存储了我 friend 的名字和最喜欢的 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,
)

显然,我向这些表中插入了一些值,但为了节省一些空间,我没有在这里提供大量的源代码。其中一小部分如下:

INSERT INTO `friends` (`id`, `name`)
VALUES
    (1,'David Belton'),
    (2,'Alex James');

INSERT INTO `teams` (`id`, `name`)
VALUES
    (1,'Cleveland Cavaliers'),
    (2,'Boston Celtics');

INSERT INTO `relations` (`friends_id`, `teams_id`)
VALUES
    (1,1),
    (2,1),
    (2,2);

在运行从数据库中获取数据并打印它们的 PHP 脚本后,我希望为我的每个 friend 提供以下类型的有效 json 输出:

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

如何使用 MySQL 为每个人创建最喜欢的球队数组?

附言 我假设最好在使用 PHP 检索数据之前在 MySQL 中完成此操作。

最佳答案

“eazy”方法是使用 CONCAT 生成 JSON。
并使用 GROUP_CONCAT 将多个团队记录组合成一个 JSON 数组。
此方法也适用于不支持创建 JSON 函数的旧 MySQL 版本。

查询

SET SESSION group_concat_max_len = @@max_allowed_packet

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"]} |

演示

http://www.sqlfiddle.com/#!9/4cd244/19

编辑了更多 friend

查询

SET SESSION group_concat_max_len = @@max_allowed_packet

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"]}] |

演示

http://www.sqlfiddle.com/#!9/4cd244/61

关于php - 如何从 3 个多对多关系表中将数组与 MySQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49279952/

相关文章:

php - CakePHP:添加用户输入以记录以及从内文件读取的数据

mysql - 在 mysql 查询中传递字符串参数时没有输出

python - 使用 urllib2 检查响应

python - 将 csv 转换为 json 多文档?

php - 即使在正确的 CFLAGS 之后,也无法在 64 位 linux 机器(AWS EC2 实例)上创建 32 位 php 扩展

php - Wordpress wp_enqueue 加载 css 但不加载 js

php - 通过 PHP 修复 MySQL 查询

C# 不四舍五入

php - Laravel:验证唯一用户名问题

PHP 检查是否有可能获得 SSL