简体   繁体   English

检索 SQL 结果,按类别分组

[英]Retrieve SQL results, grouped by categories

having a fairly low level in sql, I come to seek your help because I am blocked. sql水平相当低,我来寻求您的帮助,因为我被阻止了。

So I have a database containing my 2 tables, an article table and a category table.所以我有一个包含我的 2 个表、一个文章表和一个类别表的数据库。 In my article table, I have a field that contains the IDs of the categories to which it belongs in the JSON format.在我的文章表中,我有一个字段,其中包含它所属类别的 JSON 格式的 ID。

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.然后在 php 中我按类别对它们进行分组。 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:所以我想知道 SQL 查询是否可以通过这种方式检索已经按类别分组的文章列表:

Cat1 Cat1
- Article 1 - 第1条
- Article 2 - 第 2 条

cat2猫2
- Article 1 - 第1条
- Article 3 - 第 3 条

Cat3三类
- Article 2 - 第 2 条
- Article 3 - 第 3 条

It is better database design to make a new table ArticleCategories that lists each articles categories: 最好创建一个新表ArticleCategories来列出每个文章类别,这是更好的数据库设计:

ArticleID, CatID

Where an ArticleID can have multiple CatID... 其中ArticleID可以有多个CatID ...

Now you can associate multiple categories to one article and easily search this new database with SQL for correlations between categories and articles. 现在,您可以将多个类别关联到一篇文章,并使用SQL轻松搜索此新数据库以查找类别和文章之间的关联。

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. 因此,如scaisEdge和jStaff所建议,我设置了一个中间表,用于存储两个表的ID。

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 ? 现在是否可以通过使用GROUP BY将这些结果按类别分组以生成此表单? :

[Cat 1]
- Title 1
- Title 2

[Cat 2]
- Title 1
- Title 3

etc...

Thank you in advance. 先感谢您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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