Py学习  »  DATABASE

MySQL从另一个表更新值

coyotecipher • 4 年前 • 947 次点击  

所以这是我的表结构,如果它有帮助的话: tables

 UPDATE songs
-> SET artist_id =
-> (SELECT artist_id FROM artists WHERE artists.name = songs.artist);
Query OK, 0 rows affected (0.00 sec)
Rows matched: 27  Changed: 0  Warnings: 0

我的代码一直匹配行,但从未改变实际表中的任何内容

你知道为什么不起作用吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49265
 
947 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Tim Biegeleisen
Reply   •   1 楼
Tim Biegeleisen    4 年前

您可以在此处尝试使用更新联接:

UPDATE songs s
LEFT JOIN artists a
    ON a.name = s.artist
SET artist_id = a.artist_id;
Daniel Farrell
Reply   •   2 楼
Daniel Farrell    4 年前

更新联接的经典用例。

UPDATE songs
JOIN artists ON song.artist = artist.name
SET songs.artist_id = artists.artist_id;

然而,这些语法都不会改变数据已经是最新的这一事实。

查询正常,0行受影响(0.00秒) 匹配的行:27已更改:0警告:0

二十七 songs 行匹配这个 artist_id 每个都已设置为对应的 artists.artist_id . 所以O行被影响或改变。未生成警告。仅仅因为查询匹配行并不意味着它改变了它们。

Gordon Linoff
Reply   •   3 楼
Gordon Linoff    4 年前

这段代码基本上看起来是正确的。我会把它写成:

UPDATE songs s
    SET artist_id = (SELECT a.artist_id 
                     FROM artists a 
                     WHERE a.name = s.artist
                    );

如果此查询返回错误,则 artist_id 不在 artists . 你可能想要 a.id .

如果此查询不更新任何内容,则 艺术家id s已经具有相同的值。