[英]Right Join does not return all the records from right side table
I have two tables 我有两张桌子
Table 1 : assetdetail : itm_id,itm_slno,itm_desc,..
表1:资产详细信息:itm_id,itm_slno,itm_desc ..
Table 2 : itmtype : typ_id,typname,..
表2:itmtype:typ_id,typname,..
Table2 Contains 6 different typname. 表2包含6个不同的typname。
But when I use right join it returns only 4 records. 但是,当我使用右连接时,它仅返回4条记录。
My query is : 我的查询是:
SELECT a.itm_id,i.typname,a.itm_slno,a.itm_desc,a.itm_class from assetdetail
a right join itmtype i on i.typ_id=a.typ_id where a.itm_id!='234'
and itm_class='XYZ' group by i.typname
I need to get all the 6 typename records in the join query.What is the wrong with my query ? 我需要在联接查询中获取所有6个typename记录。查询出了什么问题?
In a right join
, conditions on the first table need to go into the on
clause, not the where
clause: 在
right join
, 第一个表上的条件需要放入on
子句,而不是where
子句:
SELECT a.itm_id, i.typname, a.itm_slno, a.itm_desc, a.itm_class
from assetdetail a right join
itmtype i
on i.typ_id = a.typ_id and a.itm_id <> '234' and a.itm_class = 'XYZ'
group by i.typname;
Non-matching rows in the first table have NULL
values, which fail the comparisons in the where
. 第一个表中的不匹配行具有
NULL
值,这会使where
的比较失败。
I would write this as a left join
, however. 但是,我将其写为
left join
。 Most people find the logic easier to follow: keep all rows in the first table, regardless of whether there is a match: 大多数人发现逻辑更容易遵循:将所有行都保留在第一个表中,无论是否存在匹配项:
SELECT a.itm_id, i.typname, a.itm_slno, a.itm_desc, a.itm_class
from itmtype i left join
assetdetail a
on i.typ_id = a.typ_id and a.itm_id <> '234' and a.itm_class = 'XYZ'
group by i.typname;
The conditions remain the same. 条件保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.