MySql 更新查询
我在 MySQL 中有一个表,其中包含以下数据,
NAME SEX
A Male
B Female
C Male
A Null
B Null
C Null
D Null
如何从前面的行更新 SEX
?
输出:
NAME SEX
A Male
B Female
C Male
A Male
B Female
C Male
D Null
提前致谢
I have a table in MySQL with following data
NAME SEX
A Male
B Female
C Male
A Null
B Null
C Null
D Null
how can I update SEX
from preceding rows?
Output:
NAME SEX
A Male
B Female
C Male
A Male
B Female
C Male
D Null
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果一个名字只能有一种性别,您可以更新所有其他还没有性别的名字,例如:
在您的示例中,这将填充除 D 之外的每一行的性别,因为没有名称为 D 和 a 的记录非空性别。
If a name can have only one sex, you can update all other names that do not have a sex yet like:
In your example, this will fill in the sex for each row except D, since there is no record with name D and a non-null sex.
如果您想在
Null
所在的所有字段上设置Male
,只需运行一个简单的更新:如果您想自动执行此操作,您应该插入一个递增索引列来引用在你的脚本中。
If you want to set
Male
on all fields whereNull
is, just run a simple update:If you want to do this automatically, you should insert an incrementing index column to refer to in your script.
如果我正确理解你想要做什么,像这样的查询就可以了
UPDATE TABLE T SET SEX = (SELECT SEX FROM TABLE WHERE NAME = T.NAME LIMIT 1);
但是mysql不能在子查询中使用更新中使用的表,所以你必须使用像这样的丑陋技巧:
MySQL 错误 1093 - 无法在 FROM 子句中指定要更新的目标表
If I understand correctly what you want to do, a query like this will be ok
UPDATE TABLE T SET SEX = (SELECT SEX FROM TABLE WHERE NAME = T.NAME LIMIT 1);
but mysql cannot use in a subquery a table used in update, so you have to use a ugly trick like this one:
MySQL Error 1093 - Can't specify target table for update in FROM clause