在单个查询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
- select all products and then
- 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?
我有一个简单的设置,其中有产品和图像。 p>
产品有很多与之相关的图像。 p>
表格如下: p>
产品: p>
- \ ñ
- PRODUCT_ID LI>
- 名称 LI>
- 描述 LI>
UL>
图片: p>
- image_id li>
- product_id li>
- name li>
- width li>
- 高度 li>
ul>
最终,我想要一个具有图像嵌套数组的产品数组。 p>
一个选项是 做两个查询 p>
- 选择所有产品,然后 li>
- 选择所有图像,然后将两者合并。 但这很慢。 li>
ol>
另一个选项是在图像上加入,然后从结果重新构建一个新数组并省略重复的产品并仅分配新的 图片。 p>
有人会建议更好的解决方案吗? p> div>
答
Try a Left Join on product_id perhaps