S
S
Sergey Dyudin2020-05-30 19:35:01
PostgreSQL
Sergey Dyudin, 2020-05-30 19:35:01

How to add records with many-to-many relationship using SQL?

Good afternoon.
I'm just starting to learn about databases and I can't figure out how to properly populate a database with many-to-many tables in Postgresql. I googled, but there are examples everywhere of how to create a connection or extract data.
For example, we have a standard case of tables Customer(id, name), Product(id, name) and a binder Cart(customer_id, product_id).
And you need to add an order from a possibly new customer with possibly new products. What is the course of action?
Should I query the Customer table and add a customer, if there is none, then make a new query and get the id of this customer, then make two queries with the Product table in the same way and after the fifth query create a new record in the Cart table with the existing id? Or is it easier to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2020-05-30
@Skywalker66

Should I query the Customer table and add a customer, if there is none, then make a new query and get the id of this customer, then make two queries with the Product table in the same way and after the fifth query create a new record in the Cart table with the existing id?
Yes. All this can be done in a stored procedure where to pass Customer_name and Product_name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question