我有一个有趣的SQL难题我无法解决,希望你们中的一个人比我更有SQL-Fu。我有两个表设置如下:
tblFormElement
FrmElementID
Label
tblFormSubmissionElement
FrmID_fk
FrmElementID_fk
SubmitID_fk
SubmissionValue
如果我运行以下SQL:
SELECT tblFormElement.Label, tblFormSubmissionElement.* FROM tblFormElement
JOIN tblFormSubmissionElement ON FrmElementID = FrmElementID_fk
WHERE FrmID_fk = 55
AND SubmitID_fk = 7062
我会得到一个如下所示的结果集:
Label | FrmID_fk | FrmElementID_fk | SubmitID_fk | SubmissionValue
Label1 | 55 | 1601 | 7062 | Foo1
Label2 | 55 | 1602 | 7062 | Foo2
Label3 | 55 | 1603 | 7062 | Foo3
Label4 | 55 | 1604 | 7062 | Foo4
Label5 | 55 | 1605 | 7062 | Foo5
现在,如果我将SubmitID_fk更改为7062以下的任何内容,我会得到如下结果:
Label | FrmID_fk | FrmElementID_fk | SubmitID_fk | SubmissionValue
Label1 | 55 | 1601 | 5011 | Foo1
Label2 | 55 | 1602 | 5011 | Foo2
Label3 | 55 | 1603 | 5011 | Foo3
Label5 | 55 | 1605 | 5011 | Foo5
What I would like to do is execute an INSERT statement for every one of these result sets which lack that Label4 row. Or in other words, For each result set which does not contain a row with FrmElementID_fk equal to 1604, INSERT the row with the respective columns. Any thoughts on how to attack this problem?
答案 0 :(得分:2)
我想你想要这样的东西。
INSERT INTO tblFormSubmissionElement
SELECT 55, 1604, SubmitID_fk, 'Foo4'
FROM tblFormSubmissionElement
WHERE SubmitID_fk < 7026
AND FrmElementID_fk = 1603;
可能有一种方法可以使用DISTINCT而不是将FrmElementID_fk与1603匹配,但我认为这也应该有用。
答案 1 :(得分:0)
使用您的选择查询:
Insert into OtherTable (
SELECT tblFormElement.Label, tblFormSubmissionElement.*
FROM tblFormElement
JOIN tblFormSubmissionElement
ON FrmElementID = FrmElementID_fk
WHERE FrmID_fk = 55
AND SubmitID_fk <> 1604)
那是你在找什么?