mysql - 仅当在 Table1 中找到要插入的值时才插入 Table2

标签 mysql sql

我有两个表 Table1 和 Table2。

我在 Table2 上使用如下插入:

insert into table2    
(colOne, colTwo, colThree) //and many more cols 
  values 
(1, norman, US) //and many more values that come from a form and not table1

我希望仅当表 1 中存在值 (1,norman, US) 时插入才能成功。值 (1,Norman,US) 来自一种形式。我怎样才能做这样的事情。

目前我用了2个步骤来做到这一点。一个检查值是否存在,两个 - 插入

最佳答案

您可以使用 INSERT INTO...SELECT...WHERE

类似的东西

insert into table2 (col1, col2, col3)
select (1, 'norman', 'US') from Table1 t1 -- where 1, 'norman', 'US' are your variables from a Form
where t1.id=1 and t1.name = 'norman' and t1.country = 'US' -- same

SqlFiddle “选择我想要的任何东西”的演示。

关于mysql - 仅当在 Table1 中找到要插入的值时才插入 Table2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517629/

相关文章:

php - UTF-8贯穿始终

MySQL 数组/项目列表和性能

php - 使用 is_numeric 验证表单输入中的整数

php - 如何将数组的格式更改为集合作为 Laravel 中的每个项目

mysql - 在 UNION 中显示 JOIN 表中的所有字段?

sql - PostgreSql:只选择周末

sql - 重写函数以不返回记录类型

java - 如何从表中删除树节点及其子记录(无级联删除)?

mysql - 计算两个日期之间一周中的特定天数

MySQL多表SELECT