简体   繁体   English

MySql将值从一行复制到另一行

[英]MySql copy value from one row to another

This should be pretty basic but i can't figure it out. 这应该是非常基本但我无法弄清楚。 Have a table 'values' 有表'价值'

entity|attribute|value

frank - shirt - red 
frank - hat   - green
sam   - shirt - blue
sam   - hat   - orange

how do i set all hats color's to be the same as the shirt color, of the same person to give frank a red hat and sam a blue hat. 我怎么设置所有的帽子颜色与衬衫颜色相同,同一个人给坦率的红帽子和山姆蓝帽子。

i was looking for a solution to this and i came up on this post. 我正在寻找解决方案,我想出了这篇文章。 however running the sql lead to a syntax error. 但是运行sql导致语法错误。

Refering to the mysql docs http://dev.mysql.com/doc/refman/5.0/en/update.html i noticed - at least in version 5 - mysql has a different syntax for this. 参考mysql文档http://dev.mysql.com/doc/refman/5.0/en/update.html我注意到 - 至少在版本5中 - mysql有不同的语法。

the general statement would be: 一般声明是:

update table t1, table t2 
set t1.field1 = t2.field2, ..., t1.fieldN = t2.fieldN
where t1.someid = t2.someid and t1.fieldX = '...' and t2.fieldY = '...'

In fact you can not use a subselect from the same table you want to run the update so the best way is to use a join. 实际上,您不能使用要运行更新的同一个表中的子选择,因此最好的方法是使用连接。

UPDATE users AS target
LEFT JOIN users AS source ON source.id = 1
SET target.name = source.name
WHERE target.id = 2;

subselects may be... 子选择可能是......

set hat color of one random shirt of some person 设置一个人的随机衬衫的帽子颜色

update values set value = (select value from values where entity = v.entity and attribute = 'shirt' limit 1) from values v where v.attribute = 'hat'

Wrote in browser, so not tested, but you can view an idea. 在浏览器中写的,所以没有经过测试,但你可以查看一个想法。

Give this a try: 尝试一下:

UPDATE table 
SET value = res.value
FROM table INNER JOIN table res
ON table.entity = res.entity
WHERE (table.attribute = 'hat') AND (res.attribute = 'shirt')

This is assuming an entity can have at most 1 shirt. 这假设一个实体最多可以有1件衬衫。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM