SQL插入查询

时间:2014-02-10 13:25:08

标签: mysql sql

我正在努力使用这条SQL,我想知道是否有人可以帮助我。

INSERT INTO table_1(
rec_1, 
rec_2, 
rec_3
) 
VALUES (
val_1, 
val_2, 
val_3
) 

现在,rec_2和rec_3是清晰的并且具有绝对值。 Rec_1填充了另一个表中的值。现在我想插入另一个表中已存在的值。我猜我应该使用WHERE NOT IN?

所以它会是这样的:

INSERT INTO table_1(
rec_1, 
rec_2, 
rec_3
) 
VALUES (
val_1,
val_2, 
val_3
) 
WHERE NOT IN (
SELECT rec FROM table_2
)

但..如何在查询中的rec_1中插入这些值?

4 个答案:

答案 0 :(得分:5)

如果INSERT/SELECTrec_2是绝对值,那么简单的rec_3如何:

INSERT INTO table_1 (rec_1, rec_2, rec_3)
SELECT val_1, 'val_2', 'val_3'
FROM other_table
WHERE val_1 NOT IN (SELECT rec_1 FROM table_1)

答案 1 :(得分:4)

INSERT INTO table_1(rec_1, rec_2, rec_3) 
SELECT val_1, val_2, val_3 FROM dual WHERE NOT EXISTS (SELECT rec FROM table_2)

您可能需要查看此answer以便进一步使用

更多详情here

答案 2 :(得分:2)

试试这个

INSERT INTO table_1(rec_1, rec_2, rec_3) 
SELECT  val_1, val_2, val_3 FROM tablename 
WHERE NOT EXISTS (SELECT rec FROM table_2)

答案 3 :(得分:0)

     4 ways to insert record
 1--> {Simple Insertion when table column sequence is known}
        Insert into Table1
        values(1,2,...)

    2--> {Simple insertion mention column}  
        Insert into Table1(col2,col4)
        values(1,2)

    3--> {bulk insertion when num of selected collumns of a table(#table2) are equal to Insertion table(Table1) }   
        Insert into Table1 {Column sequence}
        Select * -- column sequence should be same.
           from #table2

    4--> {bulk insertion when you want to insert only into desired column of a table(table1)}
        Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
        Select Column1,Column2..desired column from #table2
           from #table2