在单个查询mysql和php中选择多个关联记录

I have a simple setup, where there are Products and Images.

Products have many images associated to them.

The tables are like this:

products:

  • product_id
  • name
  • description

images:

  • image_id
  • product_id
  • name
  • width
  • height

Ultimately, I want a single array of products that has a nested array for the images.

One option is to do two queries

  1. select all products and then
  2. select all images, then merge the two. This is slow however.

The other option is to JOIN on images and then re-build a new array from the result and omit the repeated products and only assign new images.

Would anyone suggest a better solution?

Try a Left Join on product_id perhaps