简体   繁体   English

将数据插入联接表的最佳方法是什么

[英]What is the best way to insert data into joined tables

This is my table structure which i am using for the sql query: 这是我用于sql查询的表结构:

SONGS         MEDIA
id            id
track         song_id
artist        source
added_on      url

How can i insert a song (track,artist,added_on,source,url)? 如何插入歌曲(曲目,艺术家,add_on,来源,url)? MEDIA.SONG_ID needs to be the correct SONGS.ID MEDIA.SONG_ID必须为正确的SONGS.ID

MEDIA.ID and SONGS.ID are both primary and auto increment. MEDIA.ID and SONGS.ID都是主要增量和自动增量。

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: 在标准SQL中,您将在ID序列上使用事务以及nextvalcurrval函数:

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 1)第一选择

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 您可以插入SONGS,获取歌曲ID,然后将其插入MEDIA http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

2) Second option 2)第二种选择

Using updatable view (built on top of this two tables) http://dev.mysql.com/doc/refman/5.1/en/view-updatability.html 使用可更新的视图(基于这两个表) http://dev.mysql.com/doc/refman/5.1/en/view-updatability.html

3) Third option 3)第三种选择

Using stored procedure with logic similar as first option 将存储过程与第一个选项的逻辑类似

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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