我有两张桌子:
页面表包含字段id
pages2categories表包含字段page
和category
我想从页面表中选择记录
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表中存在所有三个匹配记录时,才从页面表中返回记录。
实施例
信息页:: ID
1
2
3
pages2categories :: page,pages2categories :: category
1, x
1, y
2, x
2, y
2, z
3, x
结果应该只从页面表中返回记录2。
我希望这很清楚。谢谢!
答案 0 :(得分:1)
在你的问题中你写道:
换句话说,只有在pages2categories表中存在所有三个匹配记录时,才从页面表中返回记录。
您还写道,查询应返回包含您提供的示例数据的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
答案 1 :(得分:0)
select id from table
group by id
where count(distinct category) = (select count(distinct category) from table)
答案 2 :(得分:0)
您也可以使用:
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')