I have a list of elements [a, b, c, d].
I also have a table called ticket that looks like this:
order_pnr_id bigint unsigned default '0' not null,
order_id bigint unsigned default '0' not null,
reference_ticket_id bigint unsigned default '0' not null,
I am going to insert data into a new table but I want to fetch the data from the ticket table and insert it directly. However, I also want to insert the list of elements [a, b, c, d] by iterating through the list.
I know I can use INSERT INTO SELECT FROM… clause, but how can I iterate through the list at the same time? Can I use foreach with the clause?
Ideally, I want this to work:
INSERT INTO new_table
(
order_pnr_id,
order_id,
reference_ticket_id,
new_element
)
<foreach item="elem" collection="elements" open="(" separator="," close=")">
SELECT
order_pnr_id,
order_id,
reference_ticket_id
#{elem}
FROM
ticket
WHERE
order_id = 1
</foreach>
so this inserts four rows
3
Answers
To achieve this, you can use a stored procedure or a similar construct in your database that allows for looping or iteration.
Convert your list of elements
[a, b, c, d]
to JSON array'["a", "b", "c", "d"]'
. Then use singleAdjust
new_element CHAR(1)
to proper datatype.If you are using MySQL version 8.0, you can use
WITH
clause.