mysql加入需要唯一行的位置

时间:2014-07-02 16:23:03

标签: mysql

我有2个mysql表:products和product_images。

产品:

product_id      price     discount    product_name
---------------------------------------------------
1               10.00      1.0        product 1
2               20         1.0        product 2

product_images:

product_id    images
--------------------------
1             image 1
1             image 2
1             image 3
2             image 1

等...

我需要选择每个product_id,price,discount,product_name和仅选择Product_images中的第一张图片。联接正在生成与多个图像重复的相同product_id ..

我如何编写相同的查询,以便product_id是唯一的,只有product_images表中的第一个图像???

4 个答案:

答案 0 :(得分:0)

试试:

  select p.`product_id`, `price`, `discount`, `product_name`,`images`
  from products p 
  inner join product_images pi On p.`product_id` = pi.`product_id`
  Where stock_status = 'stock' AND status = 'Enabled'
  group by p.`product_id`

DEMO

答案 1 :(得分:0)

是的,您可以使用聚合查询执行此操作,该查询采用" first"图像。

SELECT a.product_id, a.price, a.discount, a.product_name, MIN(b.image) AS image
  FROM products AS a
  LEFT JOIN product_images AS b ON a.product_id = b.product_id
 GROUP BY a.product_id, a.price, a.discount, a.product_name

这里的诀窍是聚合MIN()函数会找到"第一个"图像。

答案 2 :(得分:0)

这样的东西?

SELECT p.*,GROUP_CONTACT( pi.images )
FROM product p
LEFT JOIN product_images pi ON pi.product_id = p.product_id
GROUP BY p.product_id 

这将为您提供以逗号分隔的产品图像列表。我在这里看到的问题是你现在似乎没有办法为产品定义“第一”图像。也许你需要在product_images表中添加一个订单栏?

答案 3 :(得分:0)

正如评论中所讨论的,这是您需要的查询:

select product_id, price, discount, product_name, image
  from
     (select p.product_id, 
             p.price, 
             p.discount, 
             p.product_name,
             min(pi.id) im_id
        from products p 
               inner join products_image pi 
               on (p.product_id=pi.product_id) 
       group by p.product_id, 
             p.price, 
             p.discount, 
             p.product_name ) pd 
           inner join
         products_image pimg on ( pd.im_id = pimg.id )