【问题标题】:Possible to retrieve the SQL table including foreign key substituted to serialized data?可以检索包含替换为序列化数据的外键的 SQL 表吗?
【发布时间】:2020-05-27 03:01:25
【问题描述】:

(从评论中复制)

我使用mysql 5.7 aws aurora。 – Gurebu Bokofu


假设实体喜欢产品:

product
--------
id | name
1  | hoge
2  | fuga

有标签:

tag
---------
id | name
11 | tag1
22 | tag2

要知道,是被产品使用的标签还是现在,映射表使用:

map_product_tag
product_id | tag_id
1          | 11           <- product with ID 1 using tag with ID 11
1          | 22           <- product with ID 1 using tag with ID 22
2          | 22           <- product with ID 1 using tag with ID 22

我想通过 SQL 请求检索以下结果:

product_id | tags
             // ↓ all tags those product with ID 1 using
1          | [{ "tagId": 11, "tagName": "tag1"}, { "tagId": 22, "tagName": "tag2"}]     
             // ↓ all tags those product with ID 2 using
2          | [{ "tagId": 22, "tagName": "tag2"}]             

如果可能,请教我正确的语法。

我的数据库是 MySQL。

【问题讨论】:

  • 请用您正在运行的数据库标记您的问题:mysql、oracle、sql-server...?
  • @GMB,我标记了我的问题。
  • 我想通过 SQL 请求检索以下结果: 您的 JSON 无效。 {} 括号表示这是对象,而不是数组,它被定义为“一个对象是一组无序的名称/值对”。
  • @Akina,我会编辑。

标签: mysql sql arrays json group-by


【解决方案1】:
-- MySQL 8+ specific
select product.id product_id,
       json_arrayagg(json_object('tag_id', tag.id, 'tag_name', tag.name)) 
from map_product_tag
join product on map_product_tag.product_id = product.id
join tag on map_product_tag.tag_id = tag.id
group by product_id;
-- MySQL 5+ compatible
select product.id product_id,
       CONCAT('[', GROUP_CONCAT(json_object('tag_id', tag.id, 'tag_name', tag.name)), ']')
from map_product_tag
join product on map_product_tag.product_id = product.id
join tag on map_product_tag.tag_id = tag.id
group by product_id;

fiddle

【讨论】:

  • 感谢您的回答。不幸的是,我收到了错误ERROR 1305 (42000): FUNCTION myDataBase.json_arrayagg does not exist。版本无效?我用mysql 5.7 aws aurora
  • @GurebuBokofu 如果不是最新版本,为什么您之前没有指定您的版本?
猜你喜欢
  • 2013-05-09
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多