SQL查询将限制结果限制为每个ID一个项目

时间:2011-12-20 23:02:57

标签: mysql sql join greatest-n-per-group

所以我有2张桌子......产品和图片

Products 
---------
id
value1
value2
value3
etc..

Images
---------
id
productId
imageName

图像表每个产品将有多个图像,因此当我运行此查询时: (!= 0是因为有些图像没有productId所以我想要排除它们,不确定是否有更好的方法来处理它,或者我是否需要包含它)

select p.*, i.imageName 
from products p, images i 
where p.id = i.productId and i.productId != 0 

我得到的结果,但它给了我多个条目,我只想要每个产品一个结果,我希望它拉起第一个添加的图像(所以最老的一个)......

目前结果如下---

id : 1
imagename: name1.jpg

id : 2
imagename: name5.jpg

id: 2
imagename: name6.jpg

id: 2
imagename: name7.jpg

id: 3
imagename:  name3.jpg

etc... etc... 

我希望它看起来像这样......

id: 1
imagename: name1.jpg

id: 2
imagename: name5.jpg

id: 3
imagename: name 3.jpg

这有意义吗?任何人都可以帮我解决我的问题吗?

4 个答案:

答案 0 :(得分:3)

这样的东西会起作用,虽然你必须检查它是否有拼写错误。

SELECT p.*,
       (SELECT i.imageName
          FROM images
         WHERE i.productId = p.id
        ORDER BY i.date_created ASC
         LIMIT 1)
          AS imageName
  FROM products p

答案 1 :(得分:3)

在查询结尾处添加“group by p.id”应该可以完成工作,但现在你不知道你得到了什么样的图像。

再见

詹卢卡

答案 2 :(得分:1)

图像表中需要一个列,用于存储每个图像的添加日期和时间。然后你应该能够做到这一点(我希望,如果MySQL允许的话,不知道):

select p.*, i.imageName 
  from products p, images i 
 where p.id = i.productId 
   and i.productId != 0 
   and i.addedDate = (select min(i2.addedDate)
                        from images i2
                       where i2.productId = p.id)

答案 3 :(得分:0)

我使用images.id作为我的方法来确定最老的。您可以使用日期或日期时间字段,但如果同时为该productid添加了多个图像,您将获得多个记录,除非进一步修改查询以考虑该可能性。我猜image.id是独一无二的,所以不会有这个问题

select p.id
     , im.imageName
  from products p
left
  join ( select id
              , theDate
              , imageName
           from images
           join (select min(id) minId
                         from images
                      group 
                          by productId) oldestImages
             on oldestImages.minId = images.id
  ) im
  on im.productId = p.id
相关问题