简体   繁体   English

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

[英]SQL Insert - Only insert on this condition

I have Table 1 : 我有Table 1

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

And Table 2 : Table 2

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

I'm preforming insert into Table 1 but I would like to make a condition to only insert if the user is already available in Table 2 (only only insert row in table 1 if user already exist in table2) 我正在向表1中执行插入操作,但我想创建一个条件,使其仅在表2中已有用户时才插入(如果表2中已有用户,则仅在表1中插入行)

I'm currently doing two separate SQL checks (one if user exist then insert) but I'm sure there is a better way 我目前正在做两个单独的SQL检查(一个如果用户存在,然后插入),但是我敢肯定有更好的方法

Best way to achieve this is to define a FOREIGN KEY on the table. 实现此目的的最佳方法是在表上定义一个FOREIGN KEY This is the simplest and most implicit way to do it, some reference on that can be found on MSDN . 这是最简单,最隐式的方法,有关某些参考可以在MSDN上找到。 That means you will not ever be able to a) insert an entry to this table if no corresponding FK exists, and b) delete from the base table if entries with foreign key are here (in your case, delete the user if it already has the settings ). 这意味着您将永远无法:a)如果不存在相应的FK,则在此表中插入一个条目; b)如果此处具有外键的条目在基表中删除(在您的情况下,则删除该用户)设置)。 It will look like: 它看起来像:

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

try this on mysql: 在mysql上试试这个:

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

or this on sql server 或在SQL Server上

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

change {{ var }} to your actual values 将{{var}}更改为您的实际值

You may want to use insert ... select ... to achieve this, assuming your ID column is auto increment: 您可能要使用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