I have two tables
Table 1 : assetdetail : itm_id,itm_slno,itm_desc,..
Table 2 : itmtype : typ_id,typname,..
Table2 Contains 6 different typname.
But when I use right join it returns only 4 records.
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 ?
In a right join
, conditions on the first table need to go into the on
clause, not the where
clause:
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
.
I would write this as a left join
, however. 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.
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.