[英]How to insert name filed in the query, but to the table to pass the corresponding id of that name
I have 2 tables:我有 2 张桌子:
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 is a foreign key in bands_table
taken from genre_id in genres_table
. Genre_id 是bands_table 中的外键,取自
bands_table
中的genres_table
。
I would like to insert new rows to bands_table
, currently I do it like this:我想向
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.
However, I would like to insert not genre_id and band_name, but genre_name and band_name.但是,我想插入的不是genre_id和band_name,而是genre_name和band_name。 But, I need to keep genre_id in the table since it's connected by a FK and it needs to be so.
但是,我需要将genre_id 保留在表中,因为它是由FK 连接的,并且必须如此。
How can I achieve this?我怎样才能做到这一点? So when I insert ("Rock", "Rammstein") it will automatically compare Rock to
gender_id = 1
, and will insert instead of "Rock", 1 to gender_id.因此,当我插入 ("Rock", "Rammstein") 时,它会自动将 Rock 与
gender_id = 1
进行比较,并将插入而不是 "Rock",将 1 插入到 gender_id。
You need to insert using a select
query:您需要使用
select
查询插入:
insert into bands_table (genre_id, band_name)
select genre_id, 'Rammstein'
from genres_table
where genre_name = 'Rock';
Note, string literals should be specified with single quotes.注意,字符串文字应该用单引号指定。
in case you just want to give the genre_name and band_name and rest the query must understand to first insert the genre_name and then the band_name with the foreign key from the table genres_table..如果您只想提供genre_name 和band_name 并休息,则查询必须理解首先插入genre_name,然后插入带有表genres_table 中的外键的band_name。
you can manage the duplication by transaction lock..您可以通过事务锁管理重复..
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.