从同一行中将一个字段的值选择到同一个 MySQL 表上的另一个字段中?
如果我要将 MySQL 表转换为 PHP,它可能看起来像这样:
$table = array();
$table[0] = array ('id'=>0, 'f1'=>0, 'f2'=>1);
$table[1] = array ('id'=>1, 'f1'=>0, 'f2'=>2);
// etc...
在这种情况下,我想做这样的事情:
foreach($table as $row) {
$row['f1'] = $row['f2'];
}
是否可以使用 select 和 update 使用单个 MySQL 语句来完成此操作?
我正在想象这样的事情:
update myTable set f1=(select f2 from myTable where id=id);
除了我认为这不会起作用...我不知道如何说第二个语句中的 id 等于第一个语句中的 id。或者如何将其应用到表中的所有行。
我怎么能这样做呢?
If I were to translate my MySQL table into PHP it might look something like this:
$table = array();
$table[0] = array ('id'=>0, 'f1'=>0, 'f2'=>1);
$table[1] = array ('id'=>1, 'f1'=>0, 'f2'=>2);
// etc...
In that case, I would want to do something like this:
foreach($table as $row) {
$row['f1'] = $row['f2'];
}
Is it possible to do this with a single MySQL statement utilizing select and update?
I was imagining something like this:
update myTable set f1=(select f2 from myTable where id=id);
Except I don't think that would work... I'm not sure how to say where id in the second statement is equal to the id in the first statement. Or how to apply it to all rows in the table.
How could I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,要将 f1 值更新为与您要使用的 f2 值相同:
如果您不指定 WHERE 子句,则查询将应用于所有行。
Actually, to update the f1 values to be the same as the f2 ones you'd use:
If you don't specify a WHERE clause, the query will apply to all rows.
=
右侧的表达式是根据同一行的现有列(经常这样做,例如
SET col = col + 1
...不一定是其他列,尽管它可以)。缺少WHERE
子句意味着更新将在所有行上发生,正如您所希望的那样。Just
the expression on the right of the
=
is in terms of existing columns of the same row (one often does, e.g,SET col = col + 1
... it doesn't have to be OTHER columns, though it can). The lack of aWHERE
clause means the update will happen on all rows, as you seem to want.