简体   繁体   中英

left outer join doesnt return all rows on left table

 set @fuel_type='hsd';
select 
ro.ro_id,

(case
    when if(@fuel_type='ms',r.ms_field_input_id,r.hsd_field_input_id)= 0 
    then    if(@fuel_type='ms',concat(r.remark_ms,r.remark_branded),r.remark_hsd)
    else
    f.field_name
end )

from
retail_outlets ro left  join 
volume_trackers r on ro.ro_id=r.ro_id,
field_inputs_master f
where
    if(@fuel_type='ms',r.ms_field_input_id =   f.field_id,r.hsd_field_input_id=f.field_id) 
    and ro.pricing_module=1 and if(@fuel_type='ms',ro.ms,ro.hsd)=1 and      r.date_inserted='2017-02-06' 
    ;

I need to show all the ro_id in the retail_outlets table but only the ro_id that match with the volume trackers table are displayes

Not positive but I think this is what you're after.

changes are the following:

  1. removed , notation and inject a left join
  2. moved the r.date_inserted to the join criteria.
  3. moved where clause for , join to new left join and altered to case statement as to why I used a left join... Since we tie back to R which is already a left join it made sense to me to continue with left joins...
  4. removed some unneeded ()'s

Assumptions r.date_inserted is a varchar2 data type or '2017-02-06' is implicitly being cast correctly.

.

SET @fuel_type='hsd';

SELECT
  ro.ro_id ,

    CASE
      WHEN IF(@fuel_type='ms',r.ms_field_input_id,r.hsd_field_input_id)= 0
      THEN IF(@fuel_type='ms',concat(r.remark_ms,r.remark_branded),r.remark_hsd)
      ELSE f.field_name
    END
FROM retail_outlets ro
LEFT JOIN volume_trackers r
   ON ro.ro_id = r.ro_id
  AND r.date_inserted  = '2017-02-06'
LEFT JOIN field_inputs_master f
   ON f.field_id = CASE WHEN @fuel_type='ms' 
                        THEN r.ms_field_input_id 
                        ELSE r.hsd_field_input_id 
                   END
WHERE ro.pricing_module=1
  AND IF(@fuel_type    ='ms',ro.ms,ro.hsd)=1;

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