Search code examples
sqlunions

How to get one common value from Database using UNION


enter image description here

2 records in above image are from Db, in above table Constraint are (SID and LINE_ITEM_ID), SID and LINE_ITEM_ID both column are used to find a unique record.

My issues : I am looking for a query it should fetch the recored from DB depending on conditions if i search for PART_NUMBER = 'PAU43-IMB-P6' 1. it should fetch one record from DB if search for PART_NUMBER = 'PAU43-IMB-P6', no mater to which SID that item belong to if there is only one recored either under SID =1 or SID = 2. 2. it should fetch one record which is under SID = 2 only, from DB on search for PART_NUMBER = 'PAU43-IMB-P6', if there are 2 items one in SID=1 and other in SID=2.

i am looking for a query which will search for a given part_number depending on Both SID 1 and 2, and it should return value under SID =2 and it can return value under SID=1 only if the there are no records under SID=2 (query has to withstand a load of Million record search).

Thank you


Solution

  • Well in my case it worked something like this:

    select LINE_ITEM_ID,SID,price_1,part_number from (
    (select LINE_ITEM_ID,SID,price_1,part_number from Table where SID = 2)
     UNION 
    (select LINE_ITEM_ID,SID,price_1,part_number from Table  SID = 1 and line_item_id NOT IN (select LINE_ITEM_ID,SID,price_1,part_number from Table  SID = 2)))
    

    This query solved my issue..........