S
S
samashki7772019-07-17 23:25:41
PHP
samashki777, 2019-07-17 23:25:41

How to write a one-to-many SQL query?

Good evening, there are 2 tables - company (id, title, descr), company_images (id, company_id, image).
The site displays companies and their photos in each company card.
5d2f82a9a519e087851632.png
I can select all the photos of a certain company individually, but the problem is that I need to display several companies on the page at once and several photos of each company (cycle in a cycle). How to do it correctly using php? At the moment, I'm uploading photos using ajax, after all the companies have uploaded.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin Tsvetkov, 2019-07-18
@tsklab

Decide how you will filter companies. And then join this list with the image table (one query) or make a separate query for each company.

G
Gomonov, 2019-07-18
@Gomonov

SELECT * FROM company_images WHERE company_id IN (айди компаний через запятую)

R
Rsa97, 2019-07-18
@Rsa97

For example, like this:

SELECT `c`.`id`, `c`.`title`, `c`.`descr`, `i`.`images`
  FROM `company` AS `c`
  LEFT JOIN (
    SELECT `company_id`, GROUP_CONCAT(`image`) AS `images`
      FROM `company_images`
      GROUP BY `id`
  ) AS `i` ON `i`.`company_id` = `c`.`id`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question