gpt4 book ai didi

mysql - 如何从 MySQL 5.7 中的规范化模式中检索数据集?

转载 作者:行者123 更新时间:2023-11-29 02:40:19 25 4
gpt4 key购买 nike

我正在尝试从规范化的 MySQL 5.7 表 shema 中检索数据集,我正在努力获取值。

有 4 个表:https://www.db-fiddle.com/f/q2PJZVegdWXnpkotN2utu2/0

表 1:文章

article_id | title
1 First Car
2 Second Car

表 2:articles_attr

article_id | attr_id 
1 1
1 2
1 3
1 5
2 3
2 4

表 3:attr_groups

attr_id | attr_group_id | attribute
1 1 red
2 2 diesel
3 3 automatic
4 3 airbag
5 3 radio

表 4:attr_groups_names

attr_group_id | name
1 color
2 engine
3 features

现在我想检索具有所有属性的所有数据集(car1、car2、..),其中每组具有多个属性的数据集被聚合。

例如

article_id | title | color | engine | features
1 Car 1 red diesel automatic,radio
2 ...

组的数量很大(20 多个),所以我想避免加入太多。

我最好的镜头:

SELECT 
a.article_id,
a.title,
GROUP_CONCAT(CASE attr.attr_group_id WHEN 26 THEN cat.attr_de END) AS functions,
GROUP_CONCAT(CASE attr.attr_group_id WHEN 27 THEN cat.attr_de END) AS miscellaneous

FROM articles_attr AS attr
INNER JOIN articles a ON a.article_id = attr.article_id
INNER JOIN articles_attr AS cat ON cat.attr_id = attr.attr_id

GROUP BY a.article_id
LIMIT 3

如何做到这一点?

最佳答案

您的查询具有正确的基本结构,但您的 CASE 表达式看起来有些不对劲。试试这个版本:

SELECT
a.article_id,
a.title,
GROUP_CONCAT(CASE WHEN agn.name = 'color' THEN ag.attribute END) color,
GROUP_CONCAT(CASE WHEN agn.name = 'engine' THEN ag.attribute END) engine,
GROUP_CONCAT(CASE WHEN agn.name = 'features' THEN ag.attribute END) features
FROM articles a
INNER JOIN articles_attr aa
ON a.article_id = aa.article_id
INNER JOIN attr_groups ag
ON ag.attr_id = aa.attr_id
INNER JOIN attr_groups_names agn
ON agn.attr_group_id = ag.attr_group_id
GROUP BY
a.article_id,
a.title;

enter image description here

Demo

GROUP_CONCAT 通过忽略聚合中的 NULL 值在这里工作,然后不会将其添加到连接的字符串中。另请注意,根据您的 MySQL 版本,您可能需要 GROUP BY articles 中的 idtitle > 表格。

关于mysql - 如何从 MySQL 5.7 中的规范化模式中检索数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com