I would like to ask for a solution on how to insert n rows based on the values of a field in another table.
Consider the following tables:
CREATE TABLE Input (
ID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(128),
Ticket_Piece INT
);
CREATE TABLE Output (
Ticket_ID INT AUTO_INCREMENT PRIMARY KEY,
Transaction_ID INT,
Ticket_Number VARCHAR(23) UNIQUE,
FOREIGN KEY (Transaction_ID)
REFERENCES Input (ID)
ON UPDATE CASCADE
ON DELETE CASCADE
);
If a row from the Input
table has n in the Ticket_Number
column, then n rows should be inserted into the Output
table, with Ticket_Number
having values "ID-1" through "ID-n" (e.g. (4, "D", 5)
in Input
should result in rows with ticket numbers "4-1" through "4-5" being added to Output
). How can rows for Output
be generated in a range of numbers based on the Ticket_Piece
column using PHP and MySQL?
For example, with the input:
INSERT INTO Input (ID, Name, Ticket_Piece)
VALUES
(1, 'A', 2),
(2, 'B', 1),
(3, 'C', 3)
;
the result should be:
Ticket_ID | Transaction_ID | Ticket_Number |
---|---|---|
1 | 1 | 1-1 |
2 | 1 | 1-2 |
3 | 2 | 2-1 |
4 | 3 | 3-1 |
5 | 3 | 3-2 |
6 | 3 | 3-3 |