如何从多个MySQL表生成有效的json输出

时间:2018-03-14 15:00:51

标签: php mysql json

我在本地服务器上用phpMyAdmin创建了一个mySQL数据库。在这个数据库中,我存储了我的朋友的名字和最喜欢的NBA球队。这显然是一个多对多的关系。出于这个原因,我创建了三个表:一个带有id和amp;我的朋友的名字,一个有id&团队的名称和一个与friends_id和teams_id(这是关系表)的名称。以下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 AUTO_INCREMENT,
  `teams_id` int(4) NOT NULL AUTO_INCREMENT,
)

我想给这些数据提供一个json输出,因此我运行以下PHP脚本:

<?php

$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Friends';

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

header('Content-Type: application/json');

$sql = 'SELECT * FROM friends;';
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
$arr = [];
if ($resultCheck > 0) {
   while ($row = mysqli_fetch_assoc($result)) {
        $arr[] = $row; 
   }
} 
echo json_encode($arr, JSON_PRETTY_PRINT);

$sql = 'SELECT * FROM teams;';
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
$arr = [];
if ($resultCheck > 0) {
   while ($row = mysqli_fetch_assoc($result)) {
        $arr[] = $row; 
   }
} 
echo json_encode($arr, JSON_PRETTY_PRINT);

$sql = 'SELECT * FROM relations;';
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
$arr = [];
if ($resultCheck > 0) {
   while ($row = mysqli_fetch_assoc($result)) {
        $arr[] = $row; 
   }
} 
echo json_encode($arr, JSON_PRETTY_PRINT);
?>

然而,这并没有提供有效的json输出,而是三个不同的json数组。例如,像这样:

[..., 
{
        "id": "3",
        "name": "David Belton",
    },
...]

[..., 
{
        "id": "4",
        "name": "Boston Celtics",
    },
...]

[..., 
{
        "friends_id": "3",
        "teams_id": "4"
    },
...]

如何使用有效的json输出打印所有表?

2 个答案:

答案 0 :(得分:1)

因为这个问题与How to join arrays with MySQL from 3 tables of many-to-many relationship有关,我只发布一个MySQL答案。

<强>查询

SELECT
  CONCAT(
      "["
    , GROUP_CONCAT(json_records.json)
    , "]"
  )  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
  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

答案 1 :(得分:0)

您无需编写多个sql查询来检索它。您可以执行以下操作

<?php
$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Friends';

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

header('Content-Type: application/json');

$sql = 'SELECT * FROM friends INNER JOIN relations ON friends.id=relations.friends_id
INNER JOIN teams ON relations.teams_id=teams.id';
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
$arr = [];
if ($resultCheck > 0) {
   while ($row = mysqli_fetch_assoc($result)) {
        $arr[] = $row; 
   }
} 
echo json_encode($arr, JSON_PRETTY_PRINT);
?>