Forum Moderators: open

Message Too Old, No Replies

MySQL, inserting multiple rows based on select distinct results

         

csdude55

7:31 am on Nov 6, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm not sure if this works with pure MySQL or if I need to create a PHP script for it, so I'm hoping you guys and gals can clarify it for me.

I want to INSERT an unknown number of rows based on the results from a SELECT. What I currently do manually is:

Step 1:
SELECT DISTINCT var_1 FROM table_1 WHERE var_2 = 'foo';

Step 2:
INSERT INTO table_1 VALUES
(NULL, 'lorem', 'ipsum', '[first result from SELECT]', 'blah'),
(NULL, 'lorem', 'ipsum', '[second result from SELECT]', 'blah'),
(NULL, 'lorem', 'ipsum', '[third result from SELECT]', 'blah');

(NULL is in an auto-increment column to set an ID)

When it's 3, it's no big deal... when it's 50, it becomes a bit more work. And, of course, more lines means more of a chance of a typo.

I know that I could do a single insert like this:

INSERT INTO table_1
SELECT NULL, 'lorem', 'ipsum', var_1, 'blah'
FROM table_1 WHERE var_2 = 'foo' LIMIT 1;


But if the select returns more than one row, how do I insert a row for each of them?

I tried this and thought it would work, but I get an error that "an expression was expected near DISTINCT":

INSERT INTO table_1
SELECT NULL, 'lorem', 'ipsum', DISTINCT var_1, 'blah'
FROM table_1 WHERE var_2 = 'foo';

LifeinAsia

5:32 pm on Nov 9, 2020 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Did you try
INSERT INTO table_1
SELECT DISTINCT NULL, 'lorem', 'ipsum', var_1, 'blah'
FROM table_1 WHERE var_2 = 'foo';

Alternatively, you might try without the NULL for the auto-increment column
INSERT INTO table_1(field1,field2,field3,field4)
SELECT DISTINCT 'lorem', 'ipsum', var_1, 'blah'
FROM table_1 WHERE var_2 = 'foo';