mysql - 插入具有不同选择条件的多个值?

标签 mysql sql insert

当每个值必须首先从另一个表获取一些信息时,是否有一种方法可以插入多个值?

例如我有两张 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/

相关文章:

sql - 按 1、2 或 3+ 计算谁付了钱

mysql - SQL:加入列为空的两个表

php - MySQL 在参数之间选择查询多个,变量不工作 PHP

python - 使用 Python 将数组插入 mysql

Python 和 SQLite : insert into table

mysql - 数据模型。 ¿Pluralize or not pluralize the names of the tables?

mysql - pi 上的一次性启动脚本

Mysql SELECT 仅显示 1 个结果,而不是 3 个表中的多个结果

mysql - 按组合并行

mysql - 不重复行时插入?