sql-使用相同的用户名更新另一个表中的表值

我有两个表,同一个列名为table_b,分别表示column_b_1column_b2

我想分别从table_bcolumn_b_1column_b2复制到table_b1column_a_1column_a_2,其中user_name相同,如何在SQL语句中执行此操作?

Bin Chen asked 2019-10-07T19:04:44Z
3个解决方案
113 votes

只要有合适的索引,就可以正常工作:

UPDATE table_a
SET
      column_a_1 = (SELECT table_b.column_b_1 
                            FROM table_b
                            WHERE table_b.user_name = table_a.user_name )
    , column_a_2 = (SELECT table_b.column_b_2
                            FROM table_b
                            WHERE table_b.user_name = table_a.user_name )
WHERE
    EXISTS (
        SELECT *
        FROM table_b
        WHERE table_b.user_name = table_a.user_name
    )

sqlite3中的UPDATE不支持FROM子句,这使它比其他RDBMS中的工作更多。

如果性能不令人满意,则另一个选择可能是使用select为table_a建立新行,并与table_a联接到临时表中。 然后从table_a中删除数据,并从临时表中重新填充。

martin clayton answered 2019-10-07T19:05:10Z
10 votes

从sqlite版本3.15开始,UPDATE的语法允许使用column-name-list在SET部分中,因此查询可以写为

UPDATE table_a
SET
    (column_a_1, column_a_2) = (SELECT table_b.column_b_1, table_b.column_b_2
                                FROM table_b
                                WHERE table_b.user_name = table_a.user_name )
WHERE
    EXISTS (
       SELECT *
       FROM table_b
       WHERE table_b.user_name = table_a.user_name
   )

不仅更短而且更快

Alejadro Xalabarder answered 2019-10-07T19:05:41Z
3 votes

有一个更好的解决方案来从另一个表更新一个表:

;WITH a AS
(
    SELECT
        song_id,
        artist_id
    FROM
        online_performance
)
UPDATE record_performance
SET
    op_song_id=(SELECT song_id FROM a),
    op_artist_id=(SELECT artist_id FROM a)

;
TheFlyingDutchMoose answered 2019-10-07T19:06:07Z
translate from https://stackoverflow.com:/questions/3845718/update-table-values-from-another-table-with-the-same-user-name