Lets say i have products table
It have regular things but it also have image or collection field
Good if product have only one image or collection
But product could have multiple images like img1 img2 img3 etc
How can i keep it simple to have one filed for multiple images
Like img filed and to have img1 img2 img3?
I heard there is a way to have 2 tables one for main table and 2nd for things like this but i dont know how to set it up
2
Answers
You can use two queries:
SELECT * FROM products
Then:
SELECT * FROM product_images WHERE product_id IN (1, 2)
Where the
1, 2
are theid
s from the first query. You would match up the results of this query to the results of the first query matching onproduct_id
.There’s also a way of querying both tables at once with a LEFT JOIN. Many database access libraries have support for using one or two queries (or even choosing which way you want to do it).
You need a join table to associate a product with its images. MySQL is a "relational database" and these are the relationships.
Let’s say we have products and images.
You need a join table to relate the product with its images (and vice versa).
This is called a many-to-many relationship. A product can have many images, and the same image can be used by many products (or anything else). The IDs are declared as foreign keys so the database can confirm the referenced products and images exist, this is "referential integrity".
on delete cascade
says that when the referenced product or image is deleted, also delete its rows in product_images.Product 1 uses images 1 and 3. Product 3 uses images 2 and 3. Product 2 has no images.
Then we can match a product with its images using
join
.If we want to see all products, even those without an image, use
left join
.The "left" saying to return all rows from the "left" table. The "left" table being the one in the
from
line:products
. See Visual Representation Of SQL Joins for a great explanation of various types of joins.Demonstration.