是否可以同时进行选择和更新?
select id,name from mytable where booled = 0
UPDATE mytable SET booled=1 WHERE (select id,name from mytable where booled = 0)
所以说这两个命令合二为一。
为什么不是这个?
UPDATE mytable SET booled=1 WHERE booled=0
无需重新发明轮子——您只需要正确使用事务即可。只要您对表使用 InnoDB 引擎,MySQL 就支持事务(旧的 MyISAM 将无法工作)。
以下一系列语句可以满足您的要求:
BEGIN;
SELECT id,name FROM mytable WHERE booled=0;
UPDATE mytable SET booled=1 WHERE booled=0;
COMMIT;
根据您的编程语言和数据库驱动程序,您可能无法直接使用开始/提交事务语句,而是使用一些特定于框架的机制来执行此操作。例如,在 Perl 中,您需要执行以下操作:
my $dbh = DBI->connect(...);
$dbh->begin_work(); # This is BEGIN TRANSACTION;
my $sth = $dbh->prepare(
"SELECT id,name FROM mytable WHERE booled=0");
$sth->execute();
while (my $row = $sth->fetchrow_hashref()) {
# do something with fetched $row...
}
$sth->finish();
$dbh->do("UPDATE mytable SET booled=1 WHERE booled=0");
$dbh->commit(); # This is implicit COMMIT TRANSACTION;
尝试用分号分隔这两个语句:
select id,name from mytable where booled = 0;
UPDATE mytable SET booled=1 WHERE (select id,name from mytable where booled = 0);
你可以使用'EXISTS' ..它比“In”快得多
选择 id,name from mytable where booled = 0;
UPDATE mytable t1
SET booled=1 WHERE exists (select 1 from mytable t2
where booled = 0 and
t1.column=t2.column(join condition) );