MYSQL仅从表中显示列值一次

时间:2013-08-06 15:11:41

标签: php mysql group-concat

我有两张名称发票和invoice_product的表格。要实现可视化:

发票表

Invoice_Number  Invoice_Date  Customer_Name  Total_Amount 

     1           2013-08-01        XYZ        10000
     2           2013-08-02        ABC         7000
     3           2013-08-03        DEF         4000

invoice_product表

Invoice_Number    Product_names     Price

       1              prd1          5000
       1              prd2          3000
       1              prd3          2000
       2              prd22         3000
       2              prd25         4000
       3              prd13         2500
       3              prd16         1500

我希望通过组合两个表来获得以下输出。

Invoice_Number  Invoice_Date  Product_names Customer_Name  Total_Amount 

     1           2013-08-01        prd1          XYZ         10000
                                   prd2
                                   prd3

     2           2013-08-02        prd22         ABC         7000
                                   prd25

     3           2013-08-03        prd13         DEF         4000
                                   prd16

我尝试了以下查询。

select Invoice_Number,Invoice_Date,Product,Customer_Name,Total_Amount from invoice,invoice_product where invoice.Invoice_Number=invoice_product.invoice_Number;

我得到以下输出。

Invoice_Number  Invoice_Date  Product_names Customer_Name  Total_Amount 

     1           2013-08-01        prd1          XYZ         10000
     1           2013-08-01        prd2          XYZ         10000
     1           2013-08-01        prd3          XYZ         10000

     2           2013-08-02        prd22         ABC         7000
     2           2013-08-02        prd25         ABC         7000

     3           2013-08-03        prd13         DEF         4000
     3           2013-08-03        prd16         DEF         4000

我是否需要在查询中使用Having,Distinct,Group By之类的内容来获取所需的输出?我是mysql的新手。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

如果您真的只想要每张发票一行,但希望列出每个产品,我建议使用GROUP_CONCAT()这样的功能:

SELECT
  i.Invoice_Number AS Invoice_Number,
  i.Invoice_Date AS Invoice_Date,
  GROUP_CONCAT(ip.Product) AS products,
  i.Customer_Name AS Customer_Name,
  i.Total_Amount AS Total_Amount
FROM invoice AS i
INNER JOIN invoice_product AS ip
  ON i.Invoice_Number=ip.invoice_Number
GROUP BY i.Invoice_Number

默认情况下,GROUP_CONCAT()使用逗号作为值之间的分隔符,因此对于products列,您将获得prd1,prd2,prd3之类的值。您可以根据需要指定其他分隔符。