SQL:查询多个表的相关数据

SQL: query related data from multiple tables

我有 4 个 table,他们都以这样的方式相互关联: TB1 <- TB2 <- TB3 <- TB4 这意味着 TB4 保存属于 TB3 中单行的元素,TB3 保存属于 TB2 中单行的元素,最后 TB2 保存属于 TB1 中单行的数据。 我做这个插图是为了让它更清楚

(编辑:DB 应该是 table 中的 TB)

我已尝试通过使用子查询来实现此目的,如下所示:

SELECT TB1.id AS TB1_ID, 
    (SELECT TB2.id AS TB2_ID,
        (SELECT TB3.id AS TB3_ID,
            (SELECT TB4.id AS TB4_ID
            FROM `TB4` AS TB4 WHERE TB4.TB3_id = TB3.id) AS C
        FROM `TB3` AS TB3 WHERE TB3.TB2_id = TB2.id) AS B
    FROM `TB2` AS TB2 WHERE TB2.TB1_id = TB1.id) AS A
FROM `TB1` AS TB1

然而我的逻辑一定是有缺陷的:或者我在查询相关数据时遗漏了一些东西:因为这个 returns null,即使我知道 tables 包含所需的必要信息做出这样的交叉组合。

期望的结果是一个数组中的一组嵌套数组:每个 table 一个嵌套数组。这样我们就得到了这样的结构:

{*, A{*, B{*, C{*} } } }

因此,TB1 中的每一行都包含 TB2 中元素的多维数组作为变量,而 TB2 中的每一行都包含 TB3 中元素的多维数组作为元素,依此类推...

我也尝试将所有信息作为单独的查询提取,然后在 JS 中加入它们,但结果却很繁重:所以如果有人知道如何以正确的方式做到这一点,我将不胜感激 - 谢谢提前很多

PS。我正在通过使用 XAMPP 在我的本地环境中尝试它:这会产生问题吗?

我想你想要的是一系列JOINs:

SELECT TB1.id AS TB1_ID, TB2.id AS TB2_ID, TB3.id AS TB3_ID, TB4.id AS TB4_ID
FROM TB1
JOIN TB2 ON TB2.TB1_ID = TB1.ID
JOIN TB3 ON TB3.TB2_ID = TB2.ID
JOIN TB4 ON TB4.TB3_ID = TB3.ID

然后您可以在 PHP 中使用类似以下内容构建您想要的结构:

$sql = "SELECT TB1.id AS TB1_ID, TB2.id AS TB2_ID, TB3.id AS TB3_ID, TB4.id AS TB4_ID
FROM TB1
JOIN TB2 ON TB2.TB1_ID = TB1.ID
JOIN TB3 ON TB3.TB2_ID = TB2.ID
JOIN TB4 ON TB4.TB3_ID = TB3.ID";
$result = $conn->query($sql) or die($conn->error);
$output = array();
while ($row = $result->fetch_assoc()) {
    $tb1_id = $row['TB1_ID'];
    $tb2_id = $row['TB2_ID'];
    $tb3_id = $row['TB3_ID'];
    $tb4_id = $row['TB4_ID'];
    if (isset($output[$tb1_id][$tb2_id][$tb3_id])) {
        $output[$tb1_id][$tb2_id][$tb3_id][$tb4_id] = array();
    }
    elseif (isset($output[$tb1_id][$tb2_id])) {
        $output[$tb1_id][$tb2_id][$tb3_id] = array($tb4_id => array());
    }
    elseif (isset($output[$tb1_id])) {
        $output[$tb1_id][$tb2_id] = array($tb3_id => array($tb4_id => array()));
    }
    else {
        $output[$tb1_id] = array($tb2_id => array($tb3_id => array($tb4_id => array())));
    }
}

这里尝试使用 JSON 函数和其他应该在最新的 5.7 版本中工作的东西。

但不要问这个,因为我从这个实验中发现,在 MySql 5.7 中处理嵌套的 json 是一个真正的 PITA。

示例数据:

drop table if exists Table1;
drop table if exists Table2;
drop table if exists Table3;
drop table if exists Table4;

create table Table1 (id int primary key, col1 varchar(30));
create table Table2 (id int primary key, tbl1_id int, col1 varchar(30));
create table Table3 (id int primary key, tbl2_id int, col1 varchar(30));
create table Table4 (id int primary key, tbl3_id int, col1 varchar(30));

insert into Table1 (id, col1) values
(101, 'A1'),(102, 'A2'),(103, 'A3'),(104, 'A4');

insert into Table2 (id, tbl1_id, col1) values
(201, 101, 'B1'), (202, 102, 'B2'),(203, 103, 'B3');

insert into Table3 (id, tbl2_id, col1) values
(301, 201, 'C1'),(302, 202, 'C2');

insert into Table4 (id, tbl3_id, col1) values
(401, 301, 'D1'), (402, 301, 'D2');

查询:

SELECT t1.id AS t1id, 
GROUP_CONCAT(REPLACE(JSON_OBJECT(t1.id, JSON_ARRAY(t1.col1)),']}',', '),
IFNULL(
(
  SELECT 
  GROUP_CONCAT(
   REPLACE(JSON_OBJECT(t2.id, JSON_ARRAY(t2.col1)),']}',', '),
   IFNULL(
   (
    SELECT 
    GROUP_CONCAT(
     REPLACE(JSON_OBJECT(t3.id, JSON_ARRAY(t3.col1)),']}',', '),
     IFNULL(
     (
       SELECT 
       CONCAT('[', 
        IFNULL(GROUP_CONCAT(JSON_OBJECT(t4.id, JSON_ARRAY(t4.col1))),''), 
        ']') D
       FROM Table4 t4
       WHERE t4.tbl3_id = t3.id
       GROUP BY t4.tbl3_id
     ), '[]'), ']}') C
    FROM Table3 t3
    WHERE t3.tbl2_id = t2.id
    GROUP BY t3.tbl2_id
   ), '[]'), ']}') B
  FROM Table2 t2
  WHERE t2.tbl1_id = t1.id
  GROUP BY t2.tbl1_id
 ), '[]'), ']}') A
FROM Table1 t1
GROUP BY t1.id;

Returns:

id  A
101 {"101": ["A1", {"201": ["B1", {"301": ["C1", [{"401": ["D1"]},{"402": ["D2"]}]]}]}]}
102 {"102": ["A2", {"202": ["B2", {"302": ["C2", []]}]}]}
103 {"103": ["A3", {"203": ["B3", []]}]}
104 {"104": ["A4", []]}

db<>fiddle here

的测试