3

我在 oracle db 中有三个表,分别是 newitems、itemdetails、ticketitems 表。一些虚拟数据如下:

门票:

id    ticketid     itemid    quantity

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

商品详情:

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

新东西:

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。也欢迎任何其他解决方法。

4

3 回答 3

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'
于 2012-06-29T15:06:40.683 回答
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如果您有两个以上的明细表,请使用。

于 2012-06-29T14:54:40.940 回答
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)
于 2012-06-29T14:56:34.097 回答