如何在query中插入name字段,但是给table传递那个name对应的id

How to insert name filed in the query, but to the table to pass the corresponding id of that name

我有 2 个 table:

genres_table:                     bands_table:

genre_id | genre_name            band_id | genre_id | band_name
   1     |   Rock                   1    |    8     | Blink 182
   3     |   Jazz                   3    |    1     | Foo Fighters
   8     |   Punk                   4    |    1     | RHCP

Genre_id 是 bands_table 中的外键,取自 genres_table 中的 genre_id。

我想向 bands_table 中插入新行,目前我是这样做的:

INSERT INTO bands_table (genre_id, band_name) VALUES(1, "Rammstein") - band_id column is auto-incremented by phpmyadmin, so I don't insert it.

但是,我想插入而不是genre_id和band_name,而是genre_name 和 band_name。 但是,我需要将 genre_id 保留在 table 中,因为它是通过 FK 连接的,并且需要如此。

我怎样才能做到这一点?因此,当我插入 ("Rock", "Rammstein") 时,它会自动将 Rock 与 gender_id = 1 进行比较,并将插入而不是 "Rock",1 到 gender_id.

您需要使用 select 查询插入:

insert into bands_table (genre_id, band_name)
select genre_id, 'Rammstein'
from genres_table
where genre_name = 'Rock';

注意,字符串文字应使用单引号指定。

如果您只想给出 genre_name 和 band_name 其余查询必须了解首先插入 genre_name 然后 band_name 与外国来自 table genres_table..

的键

你可以通过事务锁来管理重复..

INSERT INTO genres_table(genre_name) VALUES ('genre_name'); 
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO bands_table(band_name,genre_id) VALUES ('band_name',@last_id_in_table1);