代码之家  ›  专栏  ›  技术社区  ›  hello_programmers

Mysql从其他表输出一列

  •  0
  • hello_programmers  · 技术社区  · 1 年前

    这是我的模式

    CREATE TABLE notes(
      id INT NOT NULL AUTO_INCREMENT,
      title VARCHAR(800),
      markdown TEXT(65535),
      PRIMARY KEY(id)
    );
    
    CREATE TABLE tags(
      id INT NOT NULL AUTO_INCREMENT,
      label VARCHAR(800),
      PRIMARY KEY(id)
    );
    
    CREATE TABLE noteTags(
      id INT NOT NULL AUTO_INCREMENT,
      noteId INT,
      tagId INT,
      PRIMARY KEY(id)
    );
    

    Notes与标记之间存在多对多关系,其中每个Notes都是唯一的,每个标记也是唯一的。我想知道我是否可以做一个选择查询,其中输出在JSON中看起来像这样。

    [
        {
            "id": 1,
            "title": "Markdown CheatSheets",
            "markdown": "### this is a markdown",
            "tagIds": [1, 3]
        }
    ]
    
    1 回复  |  直到 1 年前
        1
  •  0
  •   Jaydev Godvaishnav    1 年前

    是的,您可以在MySQL中使用带有JOIN和GROUP_CONCT的SELECT查询来实现所需的JSON输出。GROUP_CONCT函数将允许您将相关的标记ID连接到逗号分隔的字符串中,然后可以在应用程序代码中对其进行解析并转换为数组。以下是实现JSON输出的SQL查询:

    MySQL查询:

    SELECT
        n.id,
        n.title,
        n.markdown,
        CONCAT('[', GROUP_CONCAT(t.id SEPARATOR ','), ']') AS tagIds
    FROM
        notes n
    JOIN
        noteTags nt ON n.id = nt.noteId
    JOIN
        tags t ON nt.tagId = t.id
    GROUP BY
        n.id, n.title, n.markdown;
    

    输出:

    [{
        "id": 1,
        "title": "Markdown CheatSheets",
        "markdown": "### this is a markdown",
        "tagIds": "[1,3]"
    }, {
        "id": 2,
        "title": "Another Note",
        "markdown": "### Some content",
        "tagIds": "[2,3]"
    }]