mysql:如何返回嵌套数据

6rvt4ljy  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(517)

我有三张table:post,tag和post。

CREATE TABLE post (
  id INT NOT NULL,
  title VARCHAR(45) NULL,
  PRIMARY KEY (id));

CREATE TABLE tag (
  id INT NOT NULL,
  tag VARCHAR(45) NULL,
  PRIMARY KEY (id));

CREATE TABLE post_tag (
  post_id INT NOT NULL,
  tag_id INT NOT NULL,
  PRIMARY KEY (post_id, tag_id),
  INDEX fk_post_tag_tag1_idx (tag_id ASC),
  INDEX fk_post_tag_post_idx (post_id ASC),
  CONSTRAINT fk_post_tag_post
    FOREIGN KEY (post_id)
    REFERENCES post (id),
  CONSTRAINT fk_post_tag_tag1
    FOREIGN KEY (tag_id)
    REFERENCES tag (id));

INSERT INTO post (id, title) VALUES (1, 'post 1');
INSERT INTO post (id, title) VALUES (2, 'post 2');
INSERT INTO tag (id, tag) VALUES (1, 'tag 1');
INSERT INTO tag (id, tag) VALUES (2, 'tag 2');
INSERT INTO post_tag (post_id, tag_id) VALUES (1, 1);
INSERT INTO post_tag (post_id, tag_id) VALUES (1, 2);
INSERT INTO post_tag (post_id, tag_id) VALUES (2, 1);
INSERT INTO post_tag (post_id, tag_id) VALUES (2, 2);

然后我可以创建一个存储过程来检索第一篇文章及其标记:

DELIMITER $$
CREATE PROCEDURE select_posts_tags(IN id INT)
BEGIN
  SELECT *
  FROM post
    INNER JOIN post_tag pt ON post.id = pt.post_id
    INNER JOIN tag t ON t.id = pt.tag_id
      WHERE post.id = id
      GROUP BY post.id, t.id;
END $$
DELIMITER ;

最后,我从节点调用存储过程:

var mysql = require("mysql");
var connection = mysql.createConnection({
  host: "127.0.0.1",
  user: "test_database",
  password: "test_database",
  database: "test_database",
});

connection.connect();

const sql = `CALL select_posts_tags(${1})`;

connection.query(sql, (error, results) =>
  console.log(JSON.stringify(results[0], null, 4))
);

connection.end();

但结果是一个平面对象数组:

[
    {
        "id": 1,
        "title": "post 1",
        "post_id": 1,
        "tag_id": 1,
        "tag": "tag 1"
    },
    {
        "id": 2,
        "title": "post 1",
        "post_id": 1,
        "tag_id": 2,
        "tag": "tag 2"
    }
]

结果是同一个平面json对象的数组用不同的标记重复两次;
如何将标记检索为中的嵌套数组«标签» 在post对象中设置键?结果应该是:

[
  {
    id: 1,
    title: "post 1",
    tags: [
      {
        id: 1,
        tag: "tag 1",
      },
      {
        id: 2,
        tag: "tag 2",
      },
    ],
  },
];

谢谢!

soat7uwm

soat7uwm1#

你可以用 json_arrayagg() 以及 json_object() 具体如下:

SELECT 
    p.id, 
    p.title,
    json_arrayagg(json_object('id', t.id, 'tag', t.tag)) tags
FROM post p
INNER JOIN post_tag pt ON p.id = pt.post_id
INNER JOIN tag t ON t.id = pt.tag_id
WHERE p.id = ?
GROUP BY p.id, p.title;

相关问题