2016-12-16 63 views
0

更新:问题是表1有很多表2没有的行,这就是为什么查询在第一次运行时更新了多个行,但是再次运行查询时,它只更新了一个行。我不知道为什么它更新了未包含在JOIN查询中的行。带JOIN的MySQL更新 - 为什么只用一个值更新每个字段?

我需要更新表1两个领域,从两个字段的数据在表2中

我尝试这样做:

UPDATE heroku_chemical_healtheffect h, 
chebi2_compounds c 
SET h.chebi_id = c.chebi_accession, h.chebi_name = c.name 
WHERE h.name = c.name 

但它返回:1 rows affected. (Query took 0.1351 seconds.)

它插入相同的值(表2中第一行的值)分配到表1的每一行中: Rows updated

I特里d使用完整语法:

UPDATE heroku_chemical_healtheffect AS h 
INNER JOIN chebi2_compounds AS c 
ON h.name = c.name 
SET h.chebi_id = c.chebi_accession, h.chebi_name = c.name 

但发生同样的事情。我是否以错误的方式或其他方式将查询放在一起?

继承人table 2

enter image description here

当我运行SELECT与JOIN查询:

SELECT * FROM heroku_chemical_healtheffect AS h 
JOIN chebi2_compounds AS c 
ON h.name = c.name 

enter image description here

我认为也许是使用索引的问题,所以我删除来自h.chebi_idh.chebi_name的索引并将索引放在h.namec.name但它没有改变任何东西。

奇怪的是,它没有覆盖已经存在的一些值。一些h.chebi_id字段中有不同的值,并且它们保持不变。它只有它更新的空白字段。并且当它将相同的值插入到具有空白h.name字段的每一行中时,它将返回1 row(s) affected。尽管它更新了几百行。

继承人我的意思: enter image description here 它没有更新,里面有数据,即使数据是什么它所有的空行与更新不同的行。

+1

告诉我们也在其他表 –

+0

更新:新增表2至原来的职位。 –

+0

它只更新了一行,因为这是它可以找到的所有匹配行对。删除'SET'子句,将'UPDATE'替换为'SELECT * FROM'来查看匹配的行。 – axiac

回答

0

试试这个:

UPDATE 
    heroku_chemical_healtheffect 
SET 
    heroku_chemical_healtheffect.chebi_id = chebi2_compounds.chebi_accession, 
    heroku_chemical_healtheffect.chebi_name = chebi2_compounds.name 

FROM 
    heroku_chemical_healtheffect 
    INNER JOIN chebi2_compounds 
    ON heroku_chemical_healtheffect.name = chebi2_compounds.name 
+0

它给了我这个错误:'#1064 - 你的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以找到正确的语法,在'FROM heroku_chemical_healtheffect AS h INNER JOIN chebi2_compounds AS'at line 7' –

+0

@SelfDecodeSupport我编辑了我的答案 –

+1

@nimourpristou没有'FROM' ['UPDATE'语法](http://dev.mysql.com/doc/refman/5.7/en/update.html)。这个表格出现在“SET”子句之前。 – axiac