如何在mySQL中同时选择和更新一条记录?

发布于 2024-09-29 19:21:46 字数 443 浏览 3 评论 0原文

有没有什么方法可以选择一条记录并在单个查询中更新它?

我尝试了这个:

UPDATE arrc_Voucher 
  SET ActivatedDT = now() 
WHERE (SELECT VoucherNbr, VoucherID
         FROM arrc_Voucher
        WHERE ActivatedDT IS NULL
          AND BalanceInit IS NULL
          AND TypeFlag = 'V'
        LIMIT 1 )

我希望运行选择查询并获取与 where 子句匹配的第一条记录,更新该记录中的 ActivatedDT 字段,但出现以下错误:

1241 - 操作数应包含 1 列

有什么想法吗?

Is there any way to select a record and update it in a single query?

I tried this:

UPDATE arrc_Voucher 
  SET ActivatedDT = now() 
WHERE (SELECT VoucherNbr, VoucherID
         FROM arrc_Voucher
        WHERE ActivatedDT IS NULL
          AND BalanceInit IS NULL
          AND TypeFlag = 'V'
        LIMIT 1 )

which I hoped would run the select query and grab the first record that matches the where clause, the update the ActivatedDT field in that record, but I got the following error:

1241 - Operand should contain 1 column(s)

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫弦 2024-10-06 19:21:46

怎么样:

UPDATE arrc_Voucher 
  SET ActivatedDT = NOW() 
WHERE ActivatedDT IS NULL
  AND BalanceInit IS NULL
  AND TypeFlag = 'V'
LIMIT 1;

How about:

UPDATE arrc_Voucher 
  SET ActivatedDT = NOW() 
WHERE ActivatedDT IS NULL
  AND BalanceInit IS NULL
  AND TypeFlag = 'V'
LIMIT 1;
帥小哥 2024-10-06 19:21:46

来自 MySQL API 文档

UPDATE 返回实际更改的行数

您不能选择一行并同时更新它,您将需要执行两个查询才能实现它;获取您的记录,然后更新它。

如果您担心并发进程通过某种竞争条件访问同一行(假设您的用例涉及高流量),您可以考虑其他替代方案,例如 锁定表(请注意,如果表在访问时被锁定,其他进程将需要恢复--重试)

或者如果您可以创建存储过程,您可能需要阅读 本文MySQL API 文档。

但大约 99% 的情况下,这是没有必要的,这两个查询将毫无问题地执行。

From the MySQL API documentation :

UPDATE returns the number of rows that were actually changed

You cannot select a row and update it at the same time, you will need to perform two queries to achieve it; fetch your record, then update it.

If you are worrying about concurrent processes accessing the same row through some kind of race condition (supposing your use case involve high traffic), you may consider other alternatives such as locking the table (note that other processes will need to recover--retry--if the table is locked while accessing it)

Or if you can create stored procedure, you may want to read this article or the MySQL API documentation.

But about 99% of the time, this is not necessary and the two queries will execute without any problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文