3

我的头衔很糟糕,这可能就是我在 Google 上找不到我想要的东西的原因。

我想做的是从一个旧的内部博客中导出一些数据,这样我就可以将它导入到其他东西中。我的问题是,虽然我可以创建我正在寻找的那种 JOIN,但第二个表中的匹配项可以包含多行,所以我最终会得到大量重复数据。我需要从第二个表中获取结果并将这些(如果有多个匹配项)连接到查询结果中的单个字段中。查询不需要 WHERE 约束,我正在尝试检索整个 blog_posts 表。

希望这个表结构的缩写布局将有助于说明:

blog_posts              blog_categories
---------------------------------------
post_id                 post_id
post_content            category_id
post_author

这是一些示例数据。

blog_posts 表数据:

post_id  post_content  post_author
----------------------------------
1        foo1          bob
2        foo2          bob
3        foo3          fred

blog_categories 表数据:

post_id  category_id
--------------------
1        1
1        2
1        6
2        1
3        2
3        4

我理想的结果是这样的:

post_id  post_content  post_author  category_ids
------------------------------------------------
1        foo1          bob          1,2,6
2        foo2          bob          1
3        foo3          fred         2,4

我能得到的最接近的是这样一个简单的连接:

SELECT 
    blog_posts.post_id, 
    blog_posts.post_content, 
    blog_posts.post_author, 
    blog_categories.category_id 
FROM blog_posts 
    INNER JOIN blog_categories 
        ON blog_posts.post_id = blog_categories.post_id

但这会多次返回 blog_posts 表中的匹配项(每个匹配的 category_id 一次)。

有什么方法可以只使用 SQL 来完成我想要的吗?我在想某种子选择会起作用,但是我无法理解它是如何工作的 - 我知道我基本上想在我的“循环”中使用类别 ID 进行选择当前的帖子 id,但它的语法让我无法理解。它不需要高效,这是一次性操作。

4

2 回答 2

2

group_concat()功能完全符合您的需要:

SELECT 
  blog_posts.post_id, 
  blog_posts.post_content, 
  blog_posts.post_author, 
  group_concat(blog_categories.category_id)
FROM blog_posts 
JOIN blog_categories ON blog_posts.post_id = blog_categories.post_id
GROUP BY 1, 2, 3
于 2013-03-04T01:32:46.563 回答
0

你想GROUP BY blog_posts.post_id, blog_posts.post_content, blog_posts.post_author。然后使用aggregate functionhttp://en.wikipedia.org/wiki/Aggregate_function)从每个组中获取所有blog_categories.category_id值并将其转换为单个字符串。

您使用的是哪个 DBMS?对于 Postgres,您可能只需使用数组作为聚合函数:

SELECT
  blog_posts.post_id,
  blog_posts.post_content,
  blog_posts.post_author,
  ARRAY_AGG(blog_categories.category_id)
FROM blog_posts
INNER JOIN blog_categories ON blog_posts.post_id = blog_categories.post_id
GROUP BY
  blog_posts.post_id,
  blog_posts.post_content,
  blog_posts.post_author

或用于ARRAY_TO_STRING(ARRAY_AGG(blog_categories.category_id), ',')获取逗号分隔的字符串。

于 2013-03-04T01:33:25.970 回答