【问题标题】:SQL insert ID from another table by comparing data from both tablesSQL 通过比较两个表中的数据从另一个表中插入 ID
【发布时间】:2022-01-12 17:08:50
【问题描述】:

我猜这是一个简单的问题。

我有这两张桌子:

ID ARTIST NAME
1 Bad bunny
3 Jbalvin

Song ID ARTIST NAME
100 Bad bunny
101 Jbalvin

我想将第二个表的艺术家姓名替换为艺术家 ID。

谢谢!!!!

【问题讨论】:

  • 您可以使用内部联接以及匹配的艺术家名称列,例如 t1.artist_name = t2.artist_name

标签: sql oracle


【解决方案1】:

INSERT、REPLACE 等在 SQL 中具有非常精确的含义,因为它们是命令。以后请在提问时使用正确的术语。

在这种情况下,我假设您想用 ARTIST_ID 替换 ARTIST_NAME;通常这将是一个更新。但是,使用错误的列(和错误的数据类型)是不好的做法,这会使您和您的任何同事感到困惑。因此,您需要更改目标表上的列名。有多种方法可以实现这一目标;我在下面概述的一个是对错误和例外最宽容的。

所以,让我们在表 1 (artists) 和表 2 (songs) 之间建立一个外键引用。下面的示例可能包含比您需要的更多的步骤,在这种情况下省略您不想做的事情。

alter table songs add artist_id number
/

-- use MERGE to update one table with values from another

merge into songs song
using (select * from artists) artt
on (artt.artist_name = song.artist_name)
when matched then
  update song.artist_id = artt.artist_id
/

-- this step will fail if you have values of ARTIST_NAME in SONGS 
-- which don't match anything in ARTISTS 

alter table songs 
  modify artist_id not null
/

-- if the last step succeeded, normalise the data model

alter table songs
  drop column artist_name
/

此外,您应该添加一个外键(假设 ARTISTS 将 ARTIST_ID 作为主键...

alter table songs
  add constraint song_artt_fk foreign key (artist_id) references artists
/

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多