2017-03-06 51 views
0

我试图解决这个问题已经有数周的时间了,但仍然没有答案 我想显示具有相同产品条形码的inventory_table的总数量并显示其项目描述。Mysql加上group_concat并加入表

我有三个表

product_table

ID| barcode | brand | unit | price 
1 | 1111111 | Neozep | Tablet | 5.50 
2 | 2222222 | Biogesic | Syrup | 7.50 

inventory_table

ID| batch | Total| barcode 
1 | 5555555 | 100 | 1111111 
2 | 6666666 | 500 | 1111111 

productcontains_table

ID| Name  | Amount | Type | barcode 
1 | Paracetamol | 250 | mg | 1111111 
2 | Amoxicilin | 20  | ml | 1111111 

和输出应该是这样的

Barcode | Item Description      | Price | Total Qty | Amount 
1111111 | Paracetamol 250 mg | Amoxicilin 20 ml | P5.50 | 600  | P3300 

我当前的SQL语句,但这显然是错误的,希望你能帮助我的家伙 由于事先

SELECT 
GROUP_CONCAT(DISTINCT productcontains_table.name ,' ', 
    productcontains_table.Amount,' ', 
    productcontains_table.Type 
    ORDER BY productcontains_table.IDno SEPARATOR ' | ') AS ItemDescription, 

    product_table.product_price AS Price, 
    SUM(inventory_table.inventory_total) AS TotalQuantity 

    product_table.price AS Price, 
    SUM(inventory_table.total) AS TotalQuantity, 
    product_table.price * SUM(inventory_table.total) AS TotalAmount 

    FROM inventory_table 
    JOIN product_table 
    ON product_table.barcode = inventory_table.barcode 
    JOIN productcontains_table 
    ON productcontains_table.barcode = product_table.barcode 

    GROUP BY inventory_table.barcode 
+0

在这里缺少一个逗号'UMUM(inventory_table.inventory_total)AS TotalQuantity,' –

+0

是的,我只是忘了,但那是错误的。谢谢 – unknown

回答

1

修正了几个错别字:

SELECT inventory_table.barcode, 
    GROUP_CONCAT(DISTINCT productcontains_table.name,' ', productcontains_table.Amount,' ', productcontains_table.Type SEPARATOR ' | ') AS ItemDescription, 
    product_table.price AS Price, 
    SUM(inventory_table.total)/ b.cnt AS TotalQuantity, 
    product_table.price * SUM(inventory_table.total)/b.cnt AS Amount 
FROM inventory_table 
JOIN product_table ON product_table.barcode = inventory_table.barcode 
JOIN productcontains_table ON productcontains_table.barcode = product_table.barcode 
JOIN 
(SELECT barcode, 
     count(productcontains_table.name) AS cnt 
    FROM productcontains_table)b ON b.barcode=product_table.barcode 
GROUP BY inventory_table.barcode, 
    product_table.price, 
    inventory_table.barcode 

http://sqlfiddle.com/#!9/2f372/37

+0

还有一个问题,你可以看到group_concat它有两个名字,这意味着它也将总数增加两倍,所以总数不会超过3300,而是6600,因为group_concat有两个名字也会影响总金额 – unknown

+0

我认为一个由count(productcontains_table.name)'划分的部门应该完成这项工作。我无法让它在小提琴中工作 – Lightningbear

+0

对不起,我不想粗鲁,但要计算在字符串中的串联?这有什么意义? – unknown