自我内部联接获得单一记录

时间:2015-02-27 13:11:55

标签: mysql sql join

我有一个SQL表数据如下  enter image description here

我想显示产品的单一记录

例如

90792 Amlaan-Hi-Power .............. Show only 1 record when there are 2 record 
90793 Amlaan-Neutral  .............. show only 1 record when there are 2 record 
90794 Amlaan-Phosphate free .........show only 1 record when there are 2 record  
90801 Acetone .......................show only 1 record when there are 2 record 
90901 Acetanilide ...................show only 1 record when there is 1 record 

我可以使用内连接

来完成此操作

我知道

select distinct product from product ORDER BY `product`.`product` DESC

将选择不同的(唯一的)产品代码,并且只选择一个字段即产品,但是如何使用SQL语句获取其他信息会很困惑

但导致重复记录或同一表...........................

2 个答案:

答案 0 :(得分:3)

看起来您的重复行会因包中的产品数量而异。

您只能使用

显示产品和名称
SELECT DISTINCT product, name
  FROM product

如果你想处理数量,这有点棘手。这可能有效:它会将所有产品代码放在一行上。

 SELECT product,
        GROUP_CONCAT(product_code ORDER BY product_code) product_codes,
        name
   FROM product
  GROUP BY product, name

自我加入对这个应用程序没有多大意义。

答案 1 :(得分:0)

出于此目的,请使用分组依据。

SELECT product,GROUP_CONCAT(product_code SEPERATOR '|') AS product_code,name  FROM Table GROUP BY NAME

它只显示重复名称的一条记录。

产品代码的多个输入将由|分隔。