【问题标题】:SQL - Select all posts with comma separated values of categories with relations table between posts and categoriesSQL - 使用帖子和类别之间的关系表选择所有类别的逗号分隔值的帖子
【发布时间】:2021-06-12 23:22:43
【问题描述】:

我希望选择带有逗号分隔值的类别名称的帖子,如下所示:

帖子表

id post_name post_content
1 first post first post content
2 second post second post content
3 third post third post content

关系表

relation_id post_id cat_id
1 1 1
2 1 4
3 1 5
4 2 4
5 2 5
6 3 2
7 3 3

分类表

cat_id cat_name cat_slug cat_desc
1 Cat One catone lorem ipsum one
2 Cat Two cattwo lorem ipsum two
3 Cat Three catthree lorem ipsum Three
4 Cat Four catfour lorem ipsum Four
5 Cat Five catfive lorem ipsum Five

结果:

id post_name post_content cat_slug cat_name
1 first post first post content catone,catfour,catfive Cat One, Cat Four, Cat Five
2 second post second post content catfour,catfive Cat Four, Cat Five
3 third post third post content cattwo,catthree Cat Two, Cat Three

我尝试了组联系,但没有成功,它可以处理多个查询和 foreach 循环,但我想知道是否有可能只用一个查询来实现。

【问题讨论】:

  • 认真考虑处理应用代码中数据显示的问题

标签: mysql


【解决方案1】:

你试过joingroup by吗?

select p.*,
       group_concat(pc.cat_slug) as cat_slugs,
       group_concat(pc.cat_name) as cat_names
from posts p left join
     relations r
     on r.post_id = p.id left join
     post_categories pc
     on pc.cat_id = r.cat_id
group by p.id;

【讨论】:

  • 是的,我试过了,这种方式行不通,它没有使用中间的关系表。
  • @bmpf_pt 。 . .我知道了。我很困惑,因为我会调用连接表post_categories 和引用表categories。您的数据模型似乎有不同的命名约定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多