比较2个表列并更新新列

时间:2014-09-27 16:01:45

标签: sql

我有2张这样的表:

enter image description here

enter image description here

例如,在表2的第一行中,col值为3661,它等于' med'从表1中我想更新表1中的' MED'和......

这是我写的代码,但有些不对劲:(

UPDATE table1 SET
class = ( CASE 
            WHEN table2.col = table1.med
            THEN  'MED'
            --------------------------------
            WHEN table2.col = table1.mgl
            THEN  'MGL'
            --------------------------------
            WHEN table2.col = table1.rhp
            THEN  'RHP'
            --------------------------------
            WHEN table2.col = table1.epd
            THEN  'EPD'
            --------------------------------
            WHEN table2.col = table1.jpa
            THEN  'JPA'
            --------------------------------
            ELSE  'NULL'
          FROM 
            table1 LEFT outer JOIN table2
            )

3 个答案:

答案 0 :(得分:1)

你想要这样的东西:

UPDATE table1
    SET class = COALESCE((SELECT MIN(CASE WHEN table2.col = table1.med THEN 'MED'
                                          WHEN table2.col = table1.mgl THEN 'MGL'
                                          . . .
                                     END) as newval
                          FROM table2
                         ), 'NULL')

这有点棘手。如果有多个匹配项,您需要确定所需的行。以上选择匹配中的任意值。

coalesce()用于处理没有匹配的情况。在这种情况下,子查询将返回NULL

这是标准SQL,应该可以在任何数据库中使用。特定数据库可能有其他方式来编写此查询。

答案 1 :(得分:1)

我编辑了你的代码。你没有提到你使用的数据库, 无论如何试试这个:

   UPDATE table1 
    SET class = ( CASE 
                WHEN table2.col = table1.med
                THEN  'MED'
                --------------------------------
                WHEN table2.col = table1.mgl
                THEN  'MGL'
                --------------------------------
                WHEN table2.col = table1.rhp
                THEN  'RHP'
                --------------------------------
                WHEN table2.col = table1.epd
                THEN  'EPD'
                --------------------------------
                WHEN table2.col = table1.jpa
                THEN  'JPA'
                --------------------------------
                ELSE  'NULL'
    END)
    from table1 left join table2 on table1.number=table2.number

答案 2 :(得分:0)

在MySQL中尝试过,这是有效的

UPDATE Table1 
INNER JOIN Table1 T1
LEFT JOIN Table2 T2
ON T1.number = T2.number
set T1.class = 
( CASE 
  WHEN T2.col = T1.med
  THEN  'MED'
  WHEN T2.col = T1.mgl
  THEN  'MGL'
  WHEN T2.col = T1.rhp
  THEN  'RHP'
  WHEN T2.col = T1.epd
  THEN  'EPD'
  WHEN T2.col = T1.jpa
  THEN  'JPA'
  ELSE  'NULL' 
  END
  )

编辑:   对于MS SQL SERVER,您可以使用此

UPDATE Table1 
set class = 
( CASE 
  WHEN T2.col = T1.med
  THEN  'MED'
  WHEN T2.col = T1.mgl
  THEN  'MGL'
  WHEN T2.col = T1.rhp
  THEN  'RHP'
  WHEN T2.col = T1.epd
  THEN  'EPD'
  WHEN T2.col = T1.jpa
  THEN  'JPA'
  ELSE  'NULL' 
  END
  )
FROM Table1 T1
LEFT JOIN Table2 T2
ON T1.number = T2.number