复杂的sql更新

时间:2011-10-10 05:45:38

标签: mysql sql sql-update

表MyTable包含4列。

  • id,电话列是唯一的。
  • id,phone,zipcode永远不会是空的。

id - phone -        salary   - zipcode

1  - 61730459987 - $56052.45 - 02456

2 - 21249620709 - NULL -      10023

3 - 21200830859 - $39089.28 - 10023

...

10000 - 64600830857 - $46063.72 - 03795**

我需要根据来自相同邮政编码的信息将salary替换为salary_estimates来删除NULL。

至于上面的例子,第2行的NULL可以用$ 39089.28替换(我们可以从表中找到具有相同邮政编码10023的另一个人获得$ 39089.28,因此可以用$ 39089.28更新#2的NULL )。 因此,在我们运行此查询后,可以减少空单元格的数量(尽管不会达到零)。

是否有人建议针对此问题进行更新查询?

3 个答案:

答案 0 :(得分:1)

我不确定它是否适用于mysql。但是在MSSQL中你可以这样做:

UPDATE MyTable
SET salary = (select top 1 salary from MyTable where zipcode = t1.zipcode and salary is not null)
FROM MyTable t1 
WHERE t1.salary is null

您需要检查mysql的等效连接情况。

<强>参考。测试查询:

create table #temp (id int, salary decimal(18,2), zipcode varchar(10))
insert into #temp values (1,56052.45,02456)
insert into #temp values (2,NULL,1023)
insert into #temp values (3,39089.28,1023)
insert into #temp values (4,46063.72,03795)
insert into #temp values (5,NULL,02456)

UPDATE #temp
SET salary = (select top 1 salary from #temp where zipcode = t1.zipcode and salary is not null)
FROM #temp t1 
WHERE t1.salary is null

select * from #temp
drop table #temp 

答案 1 :(得分:1)

UPDATE
      MyTable AS tu
  JOIN 
      ( SELECT zipcode
             , AVG(salary) AS SalaryEstimate          --- AVG, MAX, MIN
                                                      --- your choice
        FROM MyTable 
        WHERE salary IS NOT NULL
        GROUP BY zipcode
      ) AS te
    ON te.zipcode = tu.zipcode
SET 
      tu.salary = te.SalaryEstimate
WHERE 
      tu.salary IS NULL

答案 2 :(得分:0)

你可以这样做:如果salary为null,它将替换为该邮政编码的工资。

isnull(salary,(Select top 1 salary  from  MyTable  where zipcode=10023 ))