Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mysql output a column from other tables

This is my schema

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 has a many to many relationship to tags where each note is unique and each tag is unique as well. Im wondering if I can do a select query where the output would look something like this in JSON.

[
    {
        "id": 1,
        "title": "Markdown CheatSheets",
        "markdown": "### this is a markdown",
        "tagIds": [1, 3]
    }
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, you can achieve the desired JSON output using a SELECT query with JOIN and GROUP_CONCAT in MySQL. The GROUP_CONCAT function will allow you to concatenate the related tag IDs into a comma-separated string, which can then be parsed and converted to an array in your application code. Here’s the SQL query to achieve the JSON output:

MySQL Query:

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;

Output:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading