如何在mysql的内部联接中删除重复的行

时间:2019-02-01 11:43:24

标签: mysql join

我想显示不同的卖方产品。我的sql如下:

SELECT `tblproducts`.`product_id`   ,
`tbluserproducts`.`userproduct_id`, 
 `tblproducts`.`product_name`, 
 `tblproducts`.`category_id`,
 `tbluserproducts`.`sku`, 
 `tbluserproducts`.`min_qty`,  
 `tbluserproducts`.`offer_price`, 
 MIN(tbluserproducts.offer_price) AS minimum, 
 `tbluserproducts`.`from_date`, 
 `tbluserproducts`.`to_date`, 
 `tbluserproducts`.`stock`
    FROM `tblproducts` 
     JOIN `tbluserproducts` ON tblproducts.product_id = tbluserproducts.product_id 
     WHERE (`tbluserproducts`.`status`=1) AND (`tblproducts`.`status`=1) 
     AND (`tblproducts`.`category_id`='132') 
     GROUP BY `tbluserproducts`.`userproduct_id` 
    ORDER BY product_id DESC LIMIT 5

我之所以这样输出,是因为offer_price表中的tbluserproductsproduct_id '9281'中的

相同

enter image description here

但是我想得到这样的输出

enter image description here

我的tblproducts表结构如下

  Column        Type             
  product_id    int(10) unsigned  Auto Increment 
  category_id   int(11) unsigned 
  product_name  varchar(255) 

我的tbluserproducts表结构如下

  Column    Type  Comment
  userproduct_id  int(11) unsigned Auto Increment 
  sku varchar(255)  
  product_id  int(11) unsigned  
  min_qty int(11) unsigned  
  max_qty int(11) unsigned 
  offer_price double unsigned 
  from_date date  
  to_date date  
  stock int(11) 
  insert_date datetime   
  status  tinyint(3) NULL      0-inactive,1-active,2-disabled

1 个答案:

答案 0 :(得分:0)

由于您发布的问题还不够清楚,我将假设您希望始终显示第一个不同的列来回答这个问题。

    SELECT DISTINCT ON (`tblproducts`.`product_id`) product_id,
    `tbluserproducts`.`userproduct_id`, 
    `tblproducts`.`product_name`, 
    `tblproducts`.`category_id`,
    `tbluserproducts`.`sku`, 
    `tbluserproducts`.`min_qty`,  
    `tbluserproducts`.`offer_price`, 
    MIN(tbluserproducts.offer_price) AS minimum, 
    `tbluserproducts`.`from_date`, 
    `tbluserproducts`.`to_date`, 
    `tbluserproducts`.`stock`
    FROM `tblproducts` 
    JOIN `tbluserproducts` ON tblproducts.product_id = tbluserproducts.product_id 
    WHERE (`tbluserproducts`.`status`=1) AND (`tblproducts`.`status`=1) 
    AND (`tblproducts`.`category_id`='132') 
    GROUP BY `tbluserproducts`.`userproduct_id` 
    ORDER BY product_id DESC LIMIT 5