嘗試:
select book_id
from categories
group by book_id
having sum((cat_id in (1,3))::int) = 2
或者,如果你打算從支持直接傳遞數組給它(這樣的:http://fxjr.blogspot.com/2009/05/npgsql-tips-using-in-queries-with.html)語言傳遞一個數組Postgres的,使用這樣的:
select book_id
from categories
group by book_id
having sum((cat_id = ANY(ARRAY[1,3]))::int) = 2
如果你想得到書名:
select categories.book_id, books.name
from categories
join books on books.id = categories.book_id
group by categories.book_id
,books.name
having sum((categories.cat_id in (1,3))::int) = 2
@Evan Carroll,修改查詢:
ANSI SQL的方式:
select categories.book_id, books.name
from categories
join books on books.id = categories.book_id
group by categories.book_id
,books.name
having count(case when categories.cat_id in (1,3) then 1 end) = 2
三世書名稱:
select book_id
from categories
group by book_id
having count(case when cat_id in (1,3) then 1 end) = 2
什麼是內聯的條件和相同的條款中(即其計數值的優勢。having
),而不是單獨把條件where
條款及其having
條款計數?...
select book_id
from categories
where category_id in (1,3)
group by book_id
having count(*) = 2
...如果我們兩個內嵌的條件和條款having
其計數值,我們可以很方便的我們可以通過查詢所有分類爲1和3的書籍,或者分類爲2和3和4的。面向未來的FTW!此外,對組合類別和數量的測試彼此相鄰,再加上可讀性因素。
爲了方便那種查詢:
select book_id
from categories
group by book_id
having
count(case when cat_id in (1,3) then 1 end) = 2
or count(case when cat_id in (2,3,4) then 1 end) = 3
要達到的性能(有時,實現了性能和可讀性;不要拌勻),必須複製having子句,其中的元素測試條款:
select book_id
from categories
where cat_id in (1,2,3,4)
group by book_id
having
count(case when cat_id in (1,3) then 1 end) = 2
or count(case when cat_id in (2,3,4) then 1 end) = 3
[編輯]
順便說一句,這裏的慣用MySQL的:
select book_id
from categories
group by book_id
having sum(cat_id in (1,3)) = 2
這看起來相當尷尬,而且是錯誤的。sum用於添加參數,'count()'用於對行進行計數。看到我的答案更容易做到這一點。 – 2010-06-23 14:52:58
之前你說這是錯的,這是一個習慣性的postgres。如果我使用mysql,我會這樣做:'sum(categories.cat_id in(1,3))',因爲在mysql中,布爾和整數是相同的,它們在幕後只有1和0 ,所以不需要更多的鑄造。對於postgresql,我們只需要將布爾值轉換爲整數就可以按照預期工作。好的,爲你我會使它符合ANSI SQL。編輯即將到來 – 2010-06-23 15:04:23