Sequel Pro 带有案例和随机变量的多次更新查询
好吧,我有一个表,其中的计数字段介于 0 到 100 之间。其中最多有 6 个字段与一个 id 绑定。我需要运行一个更新,将这些行中的每一行减少 1 到 3 之间的不同随机数。
我知道我可以通过以下方式获取随机值:
CAST(RAND() * 3 AS UNSIGNED)
我知道我可以让我的更新使用:(
UPDATE Info SET Info.count = CASE WHEN Info.count < 2 THEN 0 ELSE Info.count - 2 END WHERE Info.id = $iid AND Info.type = 'Active';
这只是确保我永远不会低于 0)
但我无法将它们组合起来,因为显而易见的原因是我的随机数在评估时和设置时会有所不同...
UPDATE Info SET Info.count = CASE WHEN Info.count < CAST(RAND() * 3 AS UNSIGNED) THEN 0 ELSE Info.count - CAST(RAND() * 3 AS UNSIGNED) END WHERE Info.id = $iid AND Info.type = 'Active';
现在我不想只保存 1 个变量,因为我可能需要最多6个不同的数字...有没有办法做我的事情想要在单个查询中执行操作?我知道如何以多个方式执行此操作,但每次需要更新这些块之一时,我真的不应该运行多达 6 个查询...
我正在处理的表结构是:
CREATE TABLE `Info` (
`id` int(40) DEFAULT NULL,
`count` int(11) DEFAULT NULL,
`type` varchar(40) DEFAULT NULL,
`AUTOINC` int(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`AUTOINC`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
AUTOINC 字段位于现在我可以轻松验证测试期间发生的情况。
谢谢!
Alright, so I have a table that has a count field that is between 0 and 100. Up to six of these fields are tied to a single id. I need to run an update that will decrease each of these rows by a different random number between 1 and 3.
I know I can get my random value with:
CAST(RAND() * 3 AS UNSIGNED)
And I know I can get my update to work with:
UPDATE Info SET Info.count = CASE WHEN Info.count < 2 THEN 0 ELSE Info.count - 2 END WHERE Info.id = $iid AND Info.type = 'Active';
(This just makes sure I will never dip below 0)
But I cannot combine them for the obvious reason that my random number will be different when evaluated then when it's set...
UPDATE Info SET Info.count = CASE WHEN Info.count < CAST(RAND() * 3 AS UNSIGNED) THEN 0 ELSE Info.count - CAST(RAND() * 3 AS UNSIGNED) END WHERE Info.id = $iid AND Info.type = 'Active';
Now I don't want to save just 1 variable, because I may need up to 6 different numbers...is there a way to do what I want to do in a single query? I know how I can do it in multiple, but I really shouldn't be running up to 6 queries every time I need to update one of these blocks...
The table structure I'm working off of is:
CREATE TABLE `Info` (
`id` int(40) DEFAULT NULL,
`count` int(11) DEFAULT NULL,
`type` varchar(40) DEFAULT NULL,
`AUTOINC` int(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`AUTOINC`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
The AUTOINC field at the moment is just so I can easily verify what's going on during testing.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能最好编写一个程序来执行此操作。所以你可以写一些东西到(伪代码)的程度,
或者你可以改变程序来接受一个ID,就像我以前那样,然后简单地使用一个选择和一个更新语句。
You're probably best off writing a procedure to do this. So you could write something to the extent of (pseudo code)
Or you can change the procedure to accept an ID like I had it before and simply use one select and one update statement.