繁体   English   中英

SQL插入-仅在这种情况下插入

[英]SQL Insert - Only insert on this condition

我有Table 1

ID    UserString   Date     
-------------------------
 1    KRBS         4/25/2014    
 2    WEFG         4/24/2014

Table 2

ID  UserString + Other user info 
----------------------------------
 1  KRBS    +  . . .. . 

我正在向表1中执行插入操作,但我想创建一个条件,使其仅在表2中已有用户时才插入(如果表2中已有用户,则仅在表1中插入行)

我目前正在做两个单独的SQL检查(一个如果用户存在,然后插入),但是我敢肯定有更好的方法

实现此目的的最佳方法是在表上定义一个FOREIGN KEY 这是最简单,最隐式的方法,有关某些参考可以在MSDN上找到。 这意味着您将永远无法:a)如果不存在相应的FK,则在此表中插入一个条目; b)如果此处具有外键的条目在基表中删除(在您的情况下,则删除该用户)设置)。 它看起来像:

ALTER TABLE NameOfTheTable
ADD CONSTRAINT FK_SomeNameForTheKey FOREIGN KEY (nameOfColFromThisTable)
    REFERENCES NameOfTheOtherTable (NameOfTheCOlumnYouAreReferencing);

在mysql上试试这个:

if {{ userId }} in (select UserString from Table2 where UserString = {{ userId }}) then
    insert into Table1 (ID, UserString, Date) values ({{ id }}, {{ userId }}, '{{ date }}')
end if

或在SQL Server上

if {{ userId }} in (select UserString from Table2 where UserString = {{ userId }})
    insert into Table1 (ID, UserString, Date) values ({{ id }}, {{ userId }}, '{{ date }}')

将{{var}}更改为您的实际值

您可能要使用insert ... select ...来实现这一点,假设您的ID列为自动递增:

insert into
    table1 (
        UserString,
        Date
    )
select
    table2.UserString,
    @yourDateVariableHere
from
    table2
where
    table2.UserString = @yourUserStringVariableHere

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM