存储图像数组的表:
`products` and `products_photos`
`products` includes only `id` field
`products_photos` includes `product_id` and `filename`
表值:
products
--------
id-6
id-7
products_photos
---------------
6 - filename1
6 - filename2
7 - filename3
在这两个表中, id 6 包含2张图片,但我只需要从中获取一张图片。如何在mysql或laravel中编写查询。
答案 0 :(得分:2)
如果您想获得产品的最新(最后添加)图像,那么您可以采用以下方式
注意:使用精确列代替*,以便查询执行得更快。
SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id DESC LIMIT 1;
如果您想获得产品的第一张(旧版)图像,那么您可以按照以下方式进行操作
SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id ASC LIMIT 1;
已更新:查询以获取所有记录组的列表
SELECT MAX(id) as id, photo_name FROM products_photos GROUP BY photo_name
如果您有多个列并希望获得最新记录,那么请选择
EG。考虑到您的描述列并且想要获得MAX(最新)内容而不是使用MAX,如果您需要最早使用MIN
SELECT MAX(id) as id, photo_name, MAX(description) as description FROM products_photos GROUP BY photo_name
答案 1 :(得分:0)
您可以限制查询以获得单个结果
SELECT * FROM products_photos WHERE product_id = 6 ORDER BY id LIMIT 1;
仅针对id = 6 product
提供单张图片要检索所有数据,请使用group by
SELECT * FROM GemSellerPortal.products pr
LEFT JOIN GemSellerPortal.products_photos ph
ON ph.product_id = pr.id
GROUP BY pr.id