简体   繁体   中英

SQL join over same table

在此处输入图片说明

  1. Table ORDER_ITEM has only 2 type of records. ORDER_TYPE MAT and VAL
  2. Record with ORDER_TYPE MAT does not have ITEM_ID
  3. Record with ORDER_TYPE VAL always has ITEM_ID
  4. Link between VAL and MAT is ORDER_ID. meaning one ORDER_ID can have multiple VAL but single MAT.
  5. I need to find out the ITEM_ID for which the ORDER_TYPE MAT is VALID or INVALID. As the table can be huge on a JOB_DATE. We want to put it in cache.

I tried something like this. not optimized. but this does not give intended result also. ITEM_ID of the record is null.

select * 
from   ORDER_ITEM
where  ORDER_TYPE = 'MAT' 
  and  JOB_DATE = '7/22/2016'
  and  ORDER_ID in (
                     select ORDER_ID
                     from   ORDER_ITEM 
                     where  ITEM_ID in (
                                         select ITEM_ID
                                         from   ORDER_ITEM 
                                         where  JOB_DATE = '7/22/2016'
                                            and ORDER_TYPE = 'VAL'
                                       )
                   )
;

Can I get the result using LEFT/RIGHT outer join on the same table or I need to apply programming to get the result.

I need to find the MAT records with ITEM_ID populated.

The result I am looking for is 在此处输入图片说明

Try this, let me know if not helping

select 
    mat.ORDER_ID, mat.ORDER_TYPE,val.ITEM_ID,val.VALID_INVALID 
from ORDER_ITEM mat 
    inner join ORDER_ITEM val 
        on mat.ORDER_ID = val.ORDER_ID
where mat.ORDER_TYPE='MAT' and val.ORDER_TYPE='VAL'

I think this pulls the results per your described requirements (with optional order by to get the same ordering as your example result):

select mats.order_id, mats.order_type, vals.item_id, mats.valid_invalid
from order_item mats 
join order_item vals
on (mats.order_id = vals.order_id 
    and mats.order_type = 'MAT' 
    and vals.order_type = 'VAL')
order by mats.order_id, vals.item_id;

Regarding any left join, you'd want to change to that if you also have any MAT entries that have no corresponding VAL records, and still want to retrieve those MAT results too.

SELECT
    OI1.itemid,
    OI1.order_id,
    OI2.valid_invalid
FROM OI OI1
INNER JOIN (
    SELECT
        order_id,
        valid_invalid
    FROM OI
    WHERE   Order_type = 'MAT'
) OI2 ON OI1.Order_ID = OI2.order_id
AND OI1.Itemid IS NOT NULL;

This will work for sure ;)

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