2

我有 2 张桌子:

pages 表包含字段id

pages2categories 表包含字段pagecategory

我想从 pages 表中选择记录

where (there is a record in the pages2categories table 
WHERE pages2categories::page = pages::id AND pages2categories:: category = 'X') 
AND (there is also a record in the pages2categories table WHERE pages2categories::page = pages::id AND pages2categories:: category = 'Y') 
AND (there is also a record in the pages2categories table WHERE pages2categories::page = pages::id AND pages2categories:: category = 'Z')

换句话说,只有当所有三个匹配记录都存在于 pages2categories 表中时,才从 pages 表中返回一条记录。

例子:

页面::id

1

2

3

pages2categories::page, pages2categories::category

1, x

1, y

2, x

2, y

2, z

3, x

结果应该只返回 pages 表中的记录 2。

我希望这很清楚。谢谢!

4

3 回答 3

1

你也可以使用这个:

SELECT * FROM TABLE1 A
WHERE EXISTS (SELECT * FROm TABLE2 B WHERE A.ID = B.ID AND B.category = 'X') 
AND EXISTS (SELECT * FROm TABLE2 B WHERE A.ID = B.ID AND B.category = 'Y')
AND EXISTS (SELECT * FROm TABLE2 B WHERE A.ID = B.ID AND B.category = 'Z')
于 2012-07-20T20:54:45.890 回答
1

在您的问题中,您写道:

换句话说,只有当所有三个匹配记录都存在于 pages2categories 表中时,才从 pages 表中返回一条记录。

您还写道,查询应该返回 2 行以及您提供的示例数据,但根据您的数据,只有一行包含所有 3 个类别(第 2 页)。

所以,我不确定我是否理解正确,但这是实现它的一种方法:

SELECT p.* FROM page p
LEFT JOIN pages2categories cx ON (cx.page = p.id AND cx.category = 'x')
LEFT JOIN pages2categories cy ON (cy.page = p.id AND cy.category = 'y')
LEFT JOIN pages2categories cz ON (cz.page = p.id AND cz.category = 'z')
WHERE cx.category IS NOT NULL
AND  cy.category IS NOT NULL
AND  cz.category IS NOT NULL
于 2012-07-20T21:21:59.850 回答
0
select id from table
group by id
where count(distinct category) = (select count(distinct category) from table)
于 2012-07-20T20:47:37.323 回答