创建数据库查询,根据另一个单元格的值更改值

时间:2013-12-24 11:18:52

标签: mysql sql join sql-update case

我有桌子'table_bla'

IMAGE http://gaskoncev.net/assets/table.png

请帮我创建mysql查询。

说明

  • 从float_val中选择obj_id第一个非零值,来自field_id 208,209,210
  • 如果此值> 1000且<2000,那么 将rev_val更新为1,此obj_id,其中field_id = 402
  • 如果此值> 2000且<5000,那么 将rev_val更新为2,此obj_id,其中field_id = 402
  • 如果此值> 5000且<10000,那么 将此rev_val更新为3,此obj_id,其中field_id = 402
  • 如果此值> 10000且<20000,则 将rev_val更新为4,此obj_id,其中field_id = 402
  • ..
  • 其他:5

谢谢!

2 个答案:

答案 0 :(得分:1)

UPDATE yourTable AS t1
JOIN (SELECT obj_id, MIN(float_val) AS f
      FROM yourTable
      WHERE field_id in (208, 209, 210)
      GROUP BY obj_id) t2
ON t1.obj_id = t2.obj_id
SET rel_val = CASE WHEN f BETWEEN 1001 and 1999 THEN 1
                   WHEN f BETWEEN 2001 AND 4999 THEN 2
                   WHEN f BETWEEN 5001 AND 9999 THEN 3
                   WHEN f BETWEEN 10001 AND 19999 THEN 4
                   ELSE 5
              END
WHERE t1.field_id = 402

答案 1 :(得分:0)

试试这个:

UPDATE table_bla AS t 
INNER JOIN (SELECT obj_id, float_val AS `value`
            FROM table_bla
            WHERE field_id IN (208,209,210) AND float_val IS NOT NULL
            GROUP BY obj_id) AS A ON t.obj_id = A.obj_id
SET rev_val = (CASE WHEN `value` BETWEEN 1000 AND 2000 THEN 1 
                    WHEN `value` BETWEEN 2000 AND 5000 THEN 2
                    WHEN `value` BETWEEN 5000 AND 10000 THEN 3
                    WHEN `value` BETWEEN 10000 AND 20000 THEN 4
                    ELSE 5
               END)
WHERE field_id = 402;