2010-01-12 61 views
4

我有几桌(和一些样品列)一个简单的数据库:单个SQL查询到一对多的关系

帖子(ID,标题,内容)

分类(ID,标题)

PostCategories(ID,ID_Post,ID_Category)

有没有一种方法来创建一个SQL查询w ^这将返回分配给每个职位的类别的职位?

+0

Thx for answers。我正在使用MySQL。要明确我的意思是,如果类别中有3条记录,Post中有1条记录,PostCategories中有3条记录(因此一条帖子属于三个类别),那么查询应只返回包含帖子的一行,但对于其中一列中的示例将是它所属的类别。在OOP中,它将像一个包含ID,Title,Content和(通用)类别列表属性的post对象实例。 – yojimbo87 2010-01-12 22:34:30

回答

5

可以使用GROUP_CONCAT功能

select p.*, group_concat(DISTINCT c.title ORDER BY c.title DESC SEPARATOR ', ') 
from Posts p 
inner join PostCategories pc on p.ID = pc.ID_Post 
inner join Categories c on pc.ID_Category = c.ID 
group by p.id, p.title, p.content 
+1

请注意,这将适用于当前版本的mysql,但不一定适用于其他数据库系统。 – 2010-01-14 20:27:11

1
select p.*, c.* 
from Posts p 
inner join PostCategories pc on p.ID = pc.ID_Post 
inner join Categories c on pc.ID_Category = c.ID 

如果您的意思是每篇文章只有一条记录,那么我需要知道您使用的数据库平台。

1

当然。如果我没有理解你的问题,应该是越简单

SELECT Posts.title, Categories.title 
FROM Posts, Categories, PostCategories 
WHERE PostCategories.ID_Post = Posts.ID AND PostCategories.ID_Category = Categories.ID 
ORDER BY Posts.title, Categories.title; 

获取平均每个职位一行将是一个更复杂一点,并且将取决于你所使用的RDBMS。

+0

此语法已被许多sql实现所废弃 – bleepzter 2018-02-07 01:53:43

3

简单连接正常工作。

SELECT posts.id, posts.title, categories.id, categories.title 
FROM posts 
JOIN posts_categories ON posts.id = posts_categories.post_id 
JOIN categories ON posts_categories.category_id = categories.id