简体   繁体   中英

What is the best way to insert data into joined tables

This is my table structure which i am using for the sql query:

SONGS         MEDIA
id            id
track         song_id
artist        source
added_on      url

How can i insert a song (track,artist,added_on,source,url)? MEDIA.SONG_ID needs to be the correct SONGS.ID

MEDIA.ID and SONGS.ID are both primary and auto increment.

Does anybody knows how to do this?

In standard SQL, you would use a transaction and the nextval and currval functions on the ID sequence:

BEGIN
INSERT INTO songs VALUES(nextval('songs_id_sequence'), ...);
INSERT INTO media VALUES(nextval('media_id_sequence'), currval('songs_id_sequence'), ...);
COMMIT

1) First option

you can insert into SONGS, getting song id and after it insert into MEDIA http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

2) Second option

Using updatable view (built on top of this two tables) http://dev.mysql.com/doc/refman/5.1/en/view-updatability.html

3) Third option

Using stored procedure with logic similar as first option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM