使用连接更新查询和按子句分组

时间:2011-02-04 16:23:16

标签: sql oracle oracle10g sql-update

我有以下查询,我正在尝试使用总金额更新table1。 无论如何都要一步到位吗?

select e.id
     , p.id
     , case  
         when count(distinct e.item) = 1 then 100
         when count(distinct e.item) = 2 then 150
         when count(distinct e.item) = 3 then 200
         when count(distinct e.item) = 4 then 225
         when count(distinct e.item) = 5 then 275
         when count(distinct e.item) = 6 then 325
         when count(distinct e.item) = 7 then 375
         when count(distinct e.item) = 8 then 450
         when count(distinct e.item) = 8 then 470
       end as TotalPay
  from table1 p 
  join table2 e on e.id = '111111'
               and p.id=e.itemid
group by e.id, p.id

2 个答案:

答案 0 :(得分:3)

使用:

UPDATE TABLE1
   SET total = (SELECT CASE
                         WHEN COUNT(DISTINCT t2.item) = 1 THEN 100
                         WHEN COUNT(DISTINCT t2.item) = 2 THEN 150
                         WHEN COUNT(DISTINCT t2.item) = 3 THEN 200
                         WHEN COUNT(DISTINCT t2.item) = 4 THEN 225
                         WHEN COUNT(DISTINCT t2.item) = 5 THEN 275
                         WHEN COUNT(DISTINCT t2.item) = 6 THEN 325
                         WHEN COUNT(DISTINCT t2.item) = 7 THEN 375
                         WHEN COUNT(DISTINCT t2.item) = 8 THEN 450
                         WHEN COUNT(DISTINCT t2.item) = 9 THEN 470
                       END
                  FROM TABLE2 t2
                 WHERE t2.itemid = id
                   AND t2.id = '111111'
              GROUP BY t2.id, t2.itemid)
 WHERE EXISTS(SELECT NULL
                FROM TABLE2 t
               WHERE t.itemid = id
                 AND t.id = '111111')
  • WHERE子句是必需的,否则将处理所有TABLE1行。那些没有相关TABLE2行的人会更新为NULL
  • Oracle(IME,最多10g)不支持UPDATE子句中的JOIN,如MySQL&amp; SQL Server - 您必须使用子查询(在此示例中相关)。它也不允许您为要更新的表定义表别名,因此当您在示例中看到省略表别名时 - 该列来自表而没有别名(正在更新的那个)< / LI>

答案 1 :(得分:1)

尝试:

update table1 p 
set TotalPay = 
(
select case  
         when count(distinct e.item) = 1 then 100
         when count(distinct e.item) = 2 then 150
         when count(distinct e.item) = 3 then 200
         when count(distinct e.item) = 4 then 225
         when count(distinct e.item) = 5 then 275
         when count(distinct e.item) = 6 then 325
         when count(distinct e.item) = 7 then 375
         when count(distinct e.item) = 8 then 450
         when count(distinct e.item) = 8 then 470
       end as TotalPay
  from table2 e where p.id=e.itemid
                and e.id = '111111'  
)  

正如在注释中指出的那样,即使table2中没有匹配项,上面也会更新table1中的所有行 - 它将把列设置为NULL。为了避免添加WHERE子句 - 请参阅OMGPonies的答案。