Mysql 仅当在表1中找到要插入的值时,才将其插入表2中
我有两张桌子。表一和表二 我在表2中插入如下内容:Mysql 仅当在表1中找到要插入的值时,才将其插入表2中,mysql,sql,Mysql,Sql,我有两张桌子。表一和表二 我在表2中插入如下内容: 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,norman,US)出现在表1中时成功。价值观(1,诺曼,美国)来自一种形式。我怎么能做这样的事 目前,我使
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,norman,US)出现在表1中时成功。价值观(1,诺曼,美国)来自一种形式。我怎么能做这样的事
目前,我使用了两个步骤来实现这一点。一个是检查值是否存在,二个是-插入您可以使用
插入到。。。选择。。。其中
诸如此类
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
“选择我想要的任何东西”的小演示。像这样的东西通常是用触发器完成的。为表1注册插入后触发器,并为表2执行插入
您可以使用以下方法:
INSERT INTO table2
(colOne, colTwo, colThree)
SELECT colOne, colTwo, colThree
FROM
(SELECT 1 AS colOne,'norman' AS colTwo,'US' AS colThree
UNION
SELECT 2,'sabt','US'
UNION
SELECT 3,'ebi','US'
)p
WHERE
EXISTS (
SELECT 1 FROM table1
WHERE table1.colOne = p.colOne AND
table1.colTwo =p.colTwo AND
table1.colThree =p.colThree
)
祝你好运。问题是,我无法在那里进行选择,因为插入的不仅仅是这3个值。表单中还有其他数据。所以:在表2中插入值(1,'norman','US','formfield1','formfield2')。我不认为我可以在那里选择。或者我可以吗?@Norman Yes you can:对于我(请参见查询中的注释),1、'Norman'和'US'是表单中的字段。如果不是,我应该写
选择t1.id,t1.name,t1.country
例如。Woops!在手机上查看您的答案时,评论被切断,没有滚动条。@Norman添加了一个SqlFiddle来显示如何“选择任何您喜欢的内容”。是的。非常感谢。你的解决方案很有效。我接受了你的回答。