MySQL查询转为多对多查询

发布于 2024-12-15 21:22:47 字数 357 浏览 2 评论 0原文

我有一个查询,它返回一篇文章的所有信息,但我也想返回该文章所属的类别。我该怎么做?

表/列概述:

  • 文章 - 文章 ID、发布日期、标题、摘要、内容
  • 类别 - 类别 ID、标题 文章到类别 - 文章 ID、类别 ID
  • 文章到类别 - 文章 ID、类别 ID

查询:

SELECT *, 
       UNIX_TIMESTAMP(publicationDate) AS publicationDate 
  FROM articles 
 WHERE article_id = :id

我尝试了一些不同的变体,但没有成功。

I have this query which returns all the information about an article but I also want to return which categories the article is in. How would I do that?

Table/Columns overview:

  • articles - article_id, publicationDate, title, summary, content
  • categories - category_id, title articles_to_categories - article_id, category_id
  • articles_to_categories - article_id, category_id

Query:

SELECT *, 
       UNIX_TIMESTAMP(publicationDate) AS publicationDate 
  FROM articles 
 WHERE article_id = :id

I have tried a few different variations but no success.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔岸观火 2024-12-22 21:22:47

尝试连接其他表:

SELECT
     article_id,
     UNIX_TIMESTAMP(publicationDate) AS publicationDate,
     article.title,
     article.summary,
     article.content,
     categories.title
FROM articles
JOIN articles_to_categories USING (article_id)
JOIN categories USING (category_id)
WHERE article_id = :id

您可能还想使用以下替代方法之一:

1。 GROUP_CONCAT

SELECT
     article_id,
     UNIX_TIMESTAMP(publicationDate) AS publicationDate,
     article.title,
     article.summary,
     article.content,
     GROUP_CONCAT(categories.title) AS titles
FROM articles
JOIN articles_to_categories USING (article_id)
JOIN categories USING (category_id)
WHERE article_id = :id
GROUP BY article_id

2。使用两个查询

使用现有查询,然后也使用以下查询:

SELECT title
FROM categories
JOIN articles_to_categories USING (category_id)
WHERE article_id = :id

Try joining the other tables:

SELECT
     article_id,
     UNIX_TIMESTAMP(publicationDate) AS publicationDate,
     article.title,
     article.summary,
     article.content,
     categories.title
FROM articles
JOIN articles_to_categories USING (article_id)
JOIN categories USING (category_id)
WHERE article_id = :id

You may also want to use one of the following alternative approaches:

1. GROUP_CONCAT

SELECT
     article_id,
     UNIX_TIMESTAMP(publicationDate) AS publicationDate,
     article.title,
     article.summary,
     article.content,
     GROUP_CONCAT(categories.title) AS titles
FROM articles
JOIN articles_to_categories USING (article_id)
JOIN categories USING (category_id)
WHERE article_id = :id
GROUP BY article_id

2. Use two queries

Use your existing query, then also use this one:

SELECT title
FROM categories
JOIN articles_to_categories USING (category_id)
WHERE article_id = :id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文