简体   繁体   中英

SQL Joining 2 tables: 1 `ON` vs 2 `ON`

I have a query like:

select gift.id as giftId, gift.title, count(vouchercode.id) as stock, vouchertemplate.unlimited, gift.voucherTemplate, vouchertemplate.id as voucherId,vouchertemplate.title
from gift 
inner join vouchertemplate 
left join vouchercode 
on gift.voucherTemplate = vouchertemplate.id 
on vouchertemplate.id = vouchercode.template 
and vouchercode.given = 0 
where gift.id in (13,14,15,16)

I find that this does not give me the correct result. It appears on gift.voucherTemplate = vouchertemplate.id does not work as expected. I need it before the left join. So I cannot just put all the join conditions together? I specified the table names and columns to join, so I wonder why the difference?

The below query gives me the correct result.

select gift.id as giftId, gift.title, count(vouchercode.id) as stock, vouchertemplate.unlimited, gift.voucherTemplate, vouchertemplate.id as voucherId,vouchertemplate.title
from gift 
inner join vouchertemplate 
on gift.voucherTemplate = vouchertemplate.id  <<< DIFF HERE
left join vouchercode 
on vouchertemplate.id = vouchercode.template 
and vouchercode.given = 0 
where gift.id in (13,14,15,16)

It doesnt work that way. You need to have condition for each join. you need to specify on which column (or conidtion) your two tables should be joined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM