简体   繁体   中英

Retrieve SQL results, grouped by categories

having a fairly low level in sql, I come to seek your help because I am blocked.

So I have a database containing my 2 tables, an article table and a category table. In my article table, I have a field that contains the IDs of the categories to which it belongs in the JSON format.

Schematically, the categories table looks like this:

|    Name    |  id |
|    Cat1    |  1  |
|    Cat2    |  2  |
|    Cat3    |  3  |

And the table articles:

|     Title     |   id  |       Categories      |
|     Title1    |   1   |         [1,2]         |
|     Title2    |   2   |         [1,3]         |
|     Title3    |   3   |         [2,3]         |

Currently, I retrieve my articles as follows:

SELECT *
FROM articles a
JOIN categories c
ON JSON_CONTAINS(a.categories, CAST(c.id AS CHAR))

Then in php I group them by categories. But I find that this solution is not very clean.

So I wanted to know if a SQL query could retrieve a list of articles already grouped by categories in this way:

Cat1
- Article 1
- Article 2

cat2
- Article 1
- Article 3

Cat3
- Article 2
- Article 3

It is better database design to make a new table ArticleCategories that lists each articles categories:

ArticleID, CatID

Where an ArticleID can have multiple CatID...

Now you can associate multiple categories to one article and easily search this new database with SQL for correlations between categories and articles.

SELECT    c.category, STRING_AGG(a.title, ',')
FROM      articles a
LEFT JOIN articleCategories ac
       ON a.id = ac.articleID
LEFT JOIN categories c
       ON c.id = ac.categoryID
GROUP BY  c.category

So as suggested by scaisEdge and jStaff, I set up an intermediate table where I store the id of my two tables.

Now I get a list of results in this form, which is not bad:

[0]
- Title 1
- Cat 1

[1]
- Title 1
- Cat 2

[2]
- Title 2
- Cat 1

[3]
- Title 2
- Cat 3

[4]
- Title 3
- Cat 2

[5]
- Title 3
- Cat 3

Is it possible now to group these results by categories to produce this form, maybe by using GROUP BY ? :

[Cat 1]
- Title 1
- Title 2

[Cat 2]
- Title 1
- Title 3

etc...

Thank you in advance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM