2

私は2つのテーブルを持っています:

ページテーブルにはフィールドが含まれていますid

pages2categories テーブルにはフィールドpagecategory

ページテーブルからレコードを選択したい

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')

つまり、一致する 3 つのレコードがすべて pages2categories テーブルに存在する場合にのみ、pages テーブルからレコードを返します。

例:

ページ::id

1

2

3

pages2categories::ページ、pages2categories::category

1, x

1, y

2, x

2, y

2, z

3, x

結果は、ページ テーブルからレコード 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

In your question you wrote:

In other words, returning a record from the pages table only if all three matching records exist in the pages2categories table.

You also wrote that the query should return 2 rows with the sample data you provided but based on your data, only one row has all 3 categories (page 2).

So, I'm not sure I understand it correctly but here's one way to accomplish it:

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 に答える