简体   繁体   English

SQL连接2个表:1`ON` vs 2`ON`

[英]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. 它出现on gift.voucherTemplate = vouchertemplate.id上无法正常工作。 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. 您需要指定两个表应该在哪一列(或条件)上连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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