Looping over a SQL result with multiple rows in MySQL - mysql

Let's say I have a "source table" which holds some rows, in this case four. Now I'd like to insert new rows into a "target table" for each of the rows from the source table.
My current statement is:
SET #id = 1;
INSERT INTO target_table (id, value)
VALUES (#id, 1),
(#id, 2),
(#id, 3),
(#id, 4);
However I'd like to do something like this...
SET #id = 1;
myResultSet = SELECT value FROM source_table;
FOR EACH value in myResultSet
INSERT INTO target_table (#id, #value)
END

You can use Insert ... Select statement:
INSERT INTO `target_table` (`id`, `value`)
SELECT 1, `value`
FROM `source_table`
Completely possibilities of this statement can be seen from the syntax below:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[(col_name [, col_name] ...)]
SELECT ...
[ON DUPLICATE KEY UPDATE assignment_list]
value:
{expr | DEFAULT}
assignment:
col_name = value
assignment_list:
assignment [, assignment] ...

INSERT INTO target_table ( id, value )
SELECT row_number() OVER (order by <whatever>) , value FROM source_table
or
INSERT INTO target_table( id, value )
SELECT 1, value FROM source_table
depending on what you mean

INSERT INTO target_table( id, value )
SELECT 1, value FROM source_table

Related

Can insert into table * number with same data in Mysql?

Can insert into table * number with same data in Mysql?(Yes, have same value 3 or 100 times)
INSERT INTO `test`(`name`, `test1`, `other_status`, `status`)
VALUES ('string', 'KPrBf9', 1, 0) * 3;
You need a stored procedure to insert same statement multiple times:
DELIMITER $$
CREATE PROCEDURE insert_loop ( IN nr_input bigint)
BEGIN
DECLARE counter BIGINT DEFAULT 0;
my_loop: LOOP
SET counter=counter+1;
IF counter=nr_input THEN
LEAVE my_loop;
END IF;
INSERT INTO `test`(`name`, `test1`, `other_status`, `status`)
VALUES ('string', 'KPrBf9', 1, 0);
END LOOP my_loop;
END$$
DELIMITER ;
Above procedure will insert same values based on the input parameter you give.
Call the procedure by using:
call insert_loop(5); ---number of rows to be inserted
Not sure what do you mean by *3
But if you want to insert multiple records you can use the following
INSERT INTO `test`(`name`, `test1`, `other_status`, `status`)
VALUES ('string', 'KPrBf9', 1, 0),
('string', 'KPrBf9', 1, 0),
('string', 'KPrBf9', 1, 0);
Forget about INSERT .. VALUES and study INSERT .. SELECT .
INSERT INTO table_name (columns_names) -- (`name`, `test1`, `other_status`, `status`)
WITH RECURSIVE cte AS (
SELECT 1 AS amount
UNION ALL
SELECT amount + 1 FROM cte WHERE amount < #amount_of_rows_to_insert
)
SELECT 'values list' -- 'string' AS name, 'KPrBf9' AS test1, 1 AS other_status, 0 AS status
FROM cte;
If MySQL version is too old and does not support CTE then
INSERT INTO table_name (columns_names)
SELECT 'values list'
FROM ( SELECT 1 AS amount UNION ALL
SELECT 2 UNION ALL
-- ...
SELECT #amount_of_rows_to_insert ) AS cte;

Insert string into mysql multiple times, removing last character each time, with one query

Using MySQL, I'm looking to write a single insert query that will take a single string and insert it multiple times, each time removing the last character.
So the query would be something like
INSERT INTO table (str) VALUES ("string") .....
and would result in the following values being inserted
string
strin
stri
str
st
s
I could do this PHP, but I'm wondering if there is an SQL solution first.
This approach requires that you create another table and prepopulate it with numbers, but it's easy to do and makes sense if this is something you will have to do repeatedly. I just tested this in SQLFiddle
create table table1 (string1 varchar(10));
create table table2 (number1 integer);
insert into table2 values (1);
insert into table2 values (2);
insert into table2 values (3);
insert into table2 values (4);
insert into table2 values (5);
insert into table2 values (6);
insert into table2 values (7);
insert into table2 values (8);
insert into table2 values (9);
insert into table2 values (10);
insert into table1 (string1)
select left(stringval, number1)
from (select 'ninechars' as stringval ) as a
join table2 on table2.number1 <= char_length(a.stringval)
select * from table1
STRING1
n
ni
nin
nine
ninec
ninech
ninecha
ninechar
ninechars
Of course, table2 in this case must have enough rows for the max length of the string you need to insert.
If you have a table of numbers, you could do:
insert into table(str)
select left(#str, n.n)
from (select 1 as n union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8 union all select 9
) n
where length(#str) >= n.n
order by n.n desc;
The simplest way is to write a stored procedure and then just call it to do the inserts.
DELIMITER #
CREATE PROCEDURE 'insert_string_rows' (IN 'str' text)
BEGIN
DECLARE len int unsigned;
SET len = CHAR_LENGTH(str);
WHILE len > 0 DO
INSERT INTO table VALUES (str);
SET str = SUBSTR(str, 1, len - 1);
SET len = CHAR_LENGTH(str);
END WHILE;
END#
DELIMITER ;
Then just simply
CALL insert_string_rows ("string")
and out pops all the rows into 'table'
string
strin
stri
str
st
s

SQL: How to select variable value?

I have a query
INSERT INTO ... SET ....;
SET #last_id = LAST_INSERT_ID();
INSERT INTO ... SET .... ,item_id = #last_id;
INSERT INTO ... SET .... ,item_id = #last_id;
And i want to output to result value of variable. for example:
SELECT #last_id as ID;
query:
INSERT INTO `targets` SET `name` = '123';
SET #target_id = LAST_INSERT_ID();
SELECT #target_id as id;
This is not a query, but rather a set of queries.
Just run them one by one in order.

How to use last_insert_id() in MySQL?

My SQL statements like this:
INSERT INTO foo (val1) VALUES('v1'); -- ID in first table
foo_id = SELECT last_insert_id();
INSERT INTO bar (val2) VALUES ('v2'); -- ID in second table
bar_id = SELECT last_insert_id();
INSERT INTO foobar (foo_id, bar_id, val3)
VALUES (foo_id, bar_id, 'text'); -- third table
The above is not working, it doesn't recognize the foo_id = statement.
INSERT INTO foo (val1) VALUES ('v1'); -- ID in first table
SET #foo_id = last_insert_id();
INSERT INTO bar (val2) VALUES ('v2'); -- ID in second table
SET #bar_id = last_insert_id();
INSERT INTO foobar (foo_id, bar_id, val3)
VALUES (#foo_id, #bar_id, 'text'); -- third table

SQL INSERT into MySQL table where column name includes an apostrophe

Does anyone know how I can perform an SQL INSERT operation into a MySQL table where column names include apostrophes, for example:
INSERT INTO MYTABLE (`id`, `Column'1`, `Column'2`) VALUES...
I have tried things like this but to no avail:
INSERT INTO MYTABLE (`id`, `Column''1`, `Column''2`) VALUES...
INSERT INTO MYTABLE (`id`, `Column\'1`, `Column\'2`) VALUES...
You should be able to just place backticks around the column name:
INSERT INTO MYTABLE (`id`, `Column'1`, `Column'2`) VALUES...
see SQL Fiddle with Demo
create table yourtable
(
id int,
col1 varchar(10),
`col'2` varchar(10)
);
insert into yourtable (id, col1, `col'2`) values
(1, 'test', 'sdfsd'),
(1, 'test', 'gtet')
Just put the name into a variable and use the character 39 for the apostrophe.
Example :
L'oiseau becomes :
Loiseau = 'L' + chr(39) + 'oiseau'
print(Loiseau)
=> L'oiseau