我有一个像这样的大型插入查询:
INSERT INTO video_tags
(vid_id, tag_id)
VALUES
(1,7),
(2,46),
(2,52) Etc. Etc.
但是我没有要插入的tag_ids,只有标签字符串。因此,我需要在插入标签时查找标签ID。标签存储在具有两列的查找表中:
+-----+---------+
| id | int |
| tag | varchar |
+-----+---------+
我想做这样的事情:
INSERT INTO video_tags
(vid_id, tag_id)
VALUES
(1, SELECT id FROM tags WHERE tag = 'banana'),
(2, SELECT id FROM tags WHERE tag = 'tree')
(2, SELECT id FROM tags WHERE tag = 'chimps')
...但这不起作用,无论如何看起来既麻烦又低效。
我也看到了这个:
INSERT INTO video_tags
(vid_id, tag_id)
VALUES
SELECT '1', id FROM tags WHERE tag = 'banana')
...但我无法通过多项选择来实现这一目标。
答案 0 :(得分:2)
您的查询可能是这样的:
CREATE TABLE rawdata
(`vid_id` int, `tag_name` varchar(10))
;
INSERT INTO rawdata
(`vid_id`, `tag_name`)
VALUES
(1, 'banana'),
(2, 'tree'),
(2, 'chimps')
;
INSERT INTO video_tags
SELECT rawdata.vid_id, tag.id FROM
rawdata
LEFT JOIN tag ON tag.tag = rawdata.tag_name
;
DROP TABLE rawdata
答案 1 :(得分:1)
试试这个::
INSERT INTO video_tags
(vid_id, tag_id)
VALUES
(1, (SELECT id FROM tags WHERE tag = 'banana')),
(2, (SELECT id FROM tags WHERE tag = 'tree')),
(2, SELECT id FROM tags WHERE tag = 'chimps'));