当每个值必须首先从另一个表获取一些信息时,是否有一种方法可以插入多个值?
例如我有两张 table
- 兴趣 = id,subject1
- 用户兴趣 = id、用户 ID、兴趣 ID
表的数据可能如下所示
兴趣示例表
id interests
-------------
1 cats
2 mysql
3 php
用户兴趣示例表
id user interest_id
----------------------
1 dan 1 -- dan is interested in cats
2 johan 2 -- johan is interested in mysql
3 joe 1 -- joe is interested in cats
我发现新用户 Hayley 对美国偶像和 mustache 感兴趣
兴趣示例表
id interests
-------------
1 cats
2 mysql
3 php
4 American Idol
5 beards
我想更新 userInterest 数据库以添加
id user interest_id
------------------------
4 hayley 4 -- hayley is interested in American Idol
5 hayley 5 -- hayley is interested in beards
但我不能,因为我不知道美国偶像和 mustache 的兴趣 ID 是什么?
我想在某种多重插入查询中一次性插入 Hayley 的所有兴趣。
INSERT into userInterests
Values(hayley, --whatever the id from table interests for "American Idol")
Values(hayley, --whatever the id from table interests for "beards")
我想我会在某个地方使用 SELECT 但不确定在哪里。有人可以给我提供一个如何执行此操作的示例吗?
最佳答案
用途:
INSERT INTO userInterests
SELECT DEFAULT, 'hayley', i.id
FROM INTERESTS i
WHERE i.subject1 IN ('American Idol', 'beards')
DEFAULT
是因为我假设 id
列是 AUTO_INCRMENT
。
关于mysql - 插入具有不同选择条件的多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5986399/