2015-08-22 40 views
1

我有一個SQL查詢,如:返回的行之外凡在條件

select gift.id as giftId, gift.title, count(vouchercode.id) as stock 
from gift 
inner join vouchertemplate 
left join vouchercode 
on gift.voucherTemplate = vouchertemplate.id 
and vouchertemplate.id = vouchercode.template 
and vouchercode.given = 0 
and gift.id in (5, 6, 7) 
group by gift.id 

我希望所有行有gift.id是的5,6,7一個,但我得到一排4了。這是爲什麼?

回答

2

您已離開加入。你需要:

select gift.id as giftId, gift.title, count(vouchercode.id) as stock 
from gift 
inner join vouchertemplate 
left join vouchercode 
on gift.voucherTemplate = vouchertemplate.id 
and vouchertemplate.id = vouchercode.template 
and vouchercode.given = 0 
where gift.id in (5, 6, 7) 
group by gift.id 

當你把它放在JOIN的條件 - 它只用於連接。爲此,您得到。你必須把它放在WHERE條款中。

如果此查詢不符合您的業務邏輯,請詳細解釋您需要重新設計查詢的結果。

0

當寫join S,你應該把條件每對錶之間的各join之間的on子句,在一個長on子句在末端。事實上,大多數數據庫(和ANSI)都需要這種語法。

這實際上並沒有解決您的問題。這是由on子句中的條件,而不是where條款引起的:

select g.id as giftId, g.title, count(vc.id) as stock 
from gift g inner join 
    vouchertemplate vt 
    on g.voucherTemplate = vt.id left join 
    vouchercode vc 
    on vt.id = vc.template and vc.given = 0 
where g.id in (5, 6, 7) 
group by g.id ; 

一個left join保留所有記錄在第一表無論與否on條件評價爲真。所以,在第一張桌子上過濾對left join沒有影響。同樣,對第二個表進行過濾對right join也沒有影響。

解決的辦法是在條款where條款的第一個表上。

另請注意使用表別名,以便查詢更易於編寫和讀取。