Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL INSERT INTO select

Currently using a MySQL database

Wanting to insert a new row into a table (t_2) for every matching entry in my where condition of another table (t_1).

I also want to include a count value from a seperate table for each entry (count from table counter) and a string value 'decrease' for each entry. No idea how to put this through, this is what I have so far:

INSERT INTO t_2(count,id,val='decrease')
SELECT MAX(count) as count FROM counter
SELECT id FROM t_1 WHERE val < 0

the error I am getting is:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '='decrease') SELECT count FROM counter SELECT id FROM t_1 WHERE val < 0' at line 1

I know I probably shouldn't have the val='decrease' but just wanted to illustrate I want that to be a string value inserted for each new row.

like image 977
elzaer Avatar asked May 25 '26 01:05

elzaer


1 Answers

Try this:

INSERT INTO t_2 (count,id,val) 
SELECT 
    (SELECT MAX(count) FROM counter),
    t_1.id, 
    'decrease'
FROM t_1 
WHERE val < 0,
like image 102
Marco Avatar answered May 27 '26 13:05

Marco



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!