MySQL IF判断

forget12327 2018-05-03 11:37:26
update user set balance =
if((select count(*) from user where flag = 1 )<500, balance + 1000/(500), balance + 1000/(select * from ( select count(*) from user where flag = 1 )a))
where flag = 1;

代码如上,我想实现数量小于500的话,就按照500进行计算,大于500就按照实际数进行计算,请问我写的SQL有问题吗?如果有问题的话希望能指出错误,谢谢!
...全文
714 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
forget12327 2018-05-03
  • 打赏
  • 举报
回复
引用 1 楼 wmxcn2000 的回复:

-- 使用 greatest 函数就可以了。
update user 
set balance  = (select  1000 + greatest(500, count(*)) from user where flag = 1)
where flag = 1
还有就是需要把之前的balance和计算得出的balance相加更新回去的。
forget12327 2018-05-03
  • 打赏
  • 举报
回复
引用 1 楼 wmxcn2000 的回复:

-- 使用 greatest 函数就可以了。
update user 
set balance  = (select  1000 + greatest(500, count(*)) from user where flag = 1)
where flag = 1
运行这段代码时候数据库提示You can't specify target table 'user' for update in FROM clause 用的是PHPmyadmin
shoppo0505 2018-05-03
  • 打赏
  • 举报
回复
(select * from ( select count(*) from user where flag = 1 )a) 这句什么意思? 外面那个 select * 不用吧
卖水果的net 2018-05-03
  • 打赏
  • 举报
回复

-- 使用 greatest 函数就可以了。
update user 
set balance  = (select  1000 + greatest(500, count(*)) from user where flag = 1)
where flag = 1
卖水果的net 2018-05-03
  • 打赏
  • 举报
回复

-- 完整语句
create table test(flag int, num int);
insert into test values(1,20),(1,25),(2,30);

select * from test;

-- 使用 greatest 函数就可以了。
update test
   set num = num + (select num from (select greatest(500, count(*)) num from test where flag = 1)x)
 where flag = 1;

select * from test;

drop table test;


590

社区成员

发帖
与我相关
我的任务
社区描述
提出问题
其他 技术论坛(原bbs)
社区管理员
  • community_281
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧