简体   繁体   English

在同一行的同一MySQL表上选择一个字段的值到另一个字段?

[英]Select value of one field into another on the same MySQL table in from the same row?

If I were to translate my MySQL table into PHP it might look something like this: 如果我要将MySQL表转换为PHP,它可能看起来像这样:

$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? 是否可以通过使用select和update的单个MySQL语句来做到这一点?

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. 除非我认为这行不通...我不确定如何说第二条语句中的id等于第一条语句中的id。 Or how to apply it to all rows in the table. 或者如何将其应用于表中的所有行。

How could I do this? 我该怎么办?

Actually, to update the f1 values to be the same as the f2 ones you'd use: 实际上,要将f1值更新为与您要使用的f2值相同:

UPDATE mytable
   SET f1 = f2

If you don't specify a WHERE clause, the query will apply to all rows. 如果您未指定WHERE子句,则该查询将应用于所有行。

Just 只是

UPDATE myTable SET f1 = f2

the expression on the right of the = is in terms of existing columns of the same row (one often does, eg, SET col = col + 1 ... it doesn't have to be OTHER columns, though it can ). =右边的表达式是基于同一行的现有列(经常这样做,例如SET col = col + 1 ...,虽然可以 ,但不必是OTHER列)。 The lack of a WHERE clause means the update will happen on all rows, as you seem to want. 缺少WHERE子句意味着更新将在您希望的所有行上进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 mysql从同一表中选择一个值作为另一个值 - mysql select one value as another value from same table MySQL根据另一个表中同一行的另一个字段值的重复外观更新布尔值 - MySQL updating a Boolean field value based on the duplicated appearance of another filed value of the same row from another table MySQL更新字段与来自同一表中另一个字段的值 - mysql update field with value from another field in same table 是否可以从我的MySQL数据库中的一个表中的行中获取值并插入到同一数据库中的另一个表中? - Is it possible to take a value from a row in one table in my MySQL database and insert into another table in the same database? MySQL从一个表中选择并检查另一个表是否存在相同的值 - MySQL select from a table and check in another table if the same value exists 从一个表进行MySQL查询-两次选择同一字段 - MySQL Query from one table - Select same field twice MySQL-从另一个表中查询与当前表相同的ID的字段 - mySQL - Querying a field from another table with the same id as in the current one MySQL从同一表中的另一个引用行返回值 - MySQL return value from another referenced row in the same table Select 具有一个值但没有来自同一个表的另一个值的行 - Select rows that has one value but not another from same table 从一个表中选择随机值并插入到同一数据库中的另一个?? - select randum value from one table and inserted to another in the same database??
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM