比方说,我想根据另一个单元格的值将一个值设置为多行。因此,我可以通过两种方式做到这一点:
- 选择所有项目并使用
IF
设置不同的值:
Update `table` set `a` =
if (
`b`>=100,
if (`b`>=1000, ... , 'Less than thousand') ,
'Less than hundred'
)
where `someid`='1'
- 或者做几个更新:
Update `table` set `a` = 'Less than hundred' where `someid`='1' and `b`<100;
Update `table` set `a` = 'Less than thousand' where `someid`='1' and `b`<1000 and `b`>=100;
...
哪一个在表演方面会更好?
我建议运行单个查询,并使用CASE
IF
的 insteaf 使语法更容易理解。
运行多个查询意味着多个表扫描,而此查询只执行一次扫描。
UPDATE mytable
SET a = CASE
WHEN b < 100 THEN 'Less than an hundred'
WHEN b < 1000 THEN 'Less than an thousand'
...
END
在b
上索引时,这应该非常有效。