Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL insert query

Tags:

sql

mysql

I'm struggling with this piece of SQL and I was wondering if someone could help me out.

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

Now, rec_2 and rec_3 are clear and have absolute values. Rec_1 is filled with values from another table. Now I want to insert the values from the other table which do not exist already in this table. I was guessing I should use WHERE NOT IN?

So it would be something like this:

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
)

But.. How can I insert those values in rec_1 in my query?

like image 251
Matheno Avatar asked May 23 '26 13:05

Matheno


1 Answers

How about a simple INSERT/SELECT if rec_2 and rec_3 are absolute values:

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)
like image 181
Mike Perrenoud Avatar answered May 26 '26 03:05

Mike Perrenoud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!