0

I'm trying to implement a ticket service of sorts, where each user has a certain number of tickets assigned to them. I have one table, users, that stores the name of the user and the number of tickets that will be assigned to them. But I have another table, tickets, that should have an entry for each ticket available with a foreign key that references its owner from the table users.

So, for example, if my table users contains:

User_id Name Quantity
1 Ana 3
2 Mark 4

I would like to have in my tickets table:

ticket_id user_id
1 1
2 1
3 1
4 2
5 2
6 2
7 2

Where ticket_id is serial.

Is there a easy way to insert as many rows as the quantity indicates in users? I don't want to insert them all by hand...

2
  • 1
    You can use generate_series Commented Oct 1, 2021 at 15:36
  • Or you can use a recursive CTE. But generate_series is simpler. Commented Oct 1, 2021 at 16:10

1 Answer 1

2

It could be done via Inner Join Lateral with generate_series.

Insert Into Tickets (user_id)
Select user_id
From Users Inner Join Lateral generate_series(1, Quantity) As t On true
Order by user_id
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.