Oracle Query:在单个查询中进行条件提取

时间:2012-06-29 14:40:04

标签: sql oracle

我在oracle db中有三个表作为newitems,itemdetails,ticketitems表。 一些虚拟数据如下:

TICKETITEMS:

id    ticketid     itemid    quantity

1     100          9999      2
2     100          9998      5
3     100          2222      3

ITEMDETAILS:

id    description    col_sumthing   extra_col
9999  Marlboro       val_sumthing   123_op
9998  Cigar Black    val_sumthing   456_pqwe

NEWITEMS:

id    description    col_sumthing
2222  100Pipes       val_different

最初我只需要从itemdetails + ticketitems获取数据,使用简单的连接非常容易。查询是:

SELECT "TI".*, "I"."ID" AS "ITEMID", "I"."DESCRIPTION", "I"."col_sumthing" 
  FROM "TICKETITEMS" "TI"
 INNER JOIN "ITEMDETAILS" "I" ON TI.ITEMID = I.ID
 WHERE (TI.TICKET = '100')

类似的东西。

现在引入了newitem表,其中也可能有一些项目存在于ticketitems表中。

所以我想得到一个结果:

Final Result:
id    description    itemid    quantity   col_sumthing    extra_col
1     Marlboro       9999      2          val_sumthing    123_op
2     Cigar Black    9998      5          val_sumthing    456_pqwe
3     100Pipes       2222      3          val_different   

我遇到的问题是,只有在itemdetails中找不到详细信息时才应检查NEWITEMS。还欢迎任何其他工作。

3 个答案:

答案 0 :(得分:2)

SELECT TI.ID AS "id",
       COALESCE( I.DESCRIPTION, NI.DESCRIPTION ) AS "description"
       COALESCE( I.ID, NI.ID ) AS "itemid",
       TI.QUANTITY AS "quantity"
       COALESCE( I.COL_SUMTHING, NI.COL_SUMTHING ) AS "col_sumthing"
       I.EXTRA_COL AS "extra_col"
  FROM TICKETITEMS TI
  LEFT OUTER JOIN ITEMDETAILS I ON TI.ITEMID = I.ID
  LEFT OUTER JOIN NEWITEMS NI ON I.ID IS NULL AND TI.ITEMID = NI.ID
 WHERE TI.TICKETID = '100'

答案 1 :(得分:0)

您可以使用两个OUTER连接:

SELECT ti.*, 
       nvl(i.id, n.id) itemid, 
       nvl(i.description, n.description) description, 
       nvl(i.col_sumthing, n.col_sumthing) col_sumthing 
  FROM ticketitems ti
  LEFT JOIN itemdetails i ON ti.itemid = i.id
  LEFT JOIN newsitems n ON ti.itemid = n.id
 WHERE ti.ticket = '100'

只要两个详细信息表都将ID作为主键,这将有效。如果您有两个以上的明细表,请使用COALESCE

答案 2 :(得分:0)

您需要使用ITEMDETAILS和NEWITEMS表的UNION,但是需要对数据进行排名并仅获取相关行。

select 
  ti.id, 
  it.description, 
  it.id as itemid, 
  ti.quantity, 
  it.col_sumthing, 
  it.extra_col
from 
  ticketitem ti
  join (
    select 
      id,  
      description,  
      col_sumthing,  
      extra_col,  
      row_number() over (partition by id order by item_ordering) as item_priority
    from (
      select id, description, col_sumthing, extra_col, 1 as item_ordering
      from itemdetails
      union all
      select id, description, col_sumthing, null as extra_col, 2 as item_ordering
      from newitems 
    )
  ) it on (it.id = ti.itemid and it.item_priority = 1)