从具有相同列

时间:2017-05-23 07:46:33

标签: mysql

我有一个产品表,sales_item和一个具有以下结构的股票

产品表:

+----+-----+-------------+
| id |name |description  |
+----+-----+-------------+
| 1  |Pr1  |prod1        |
+----+-----+-------------+
| 2  |Pr2  |prod2        |
+----+-----+-------------+
| .. |...  |.....        |
+----+-----+-------------+

sales_item_details表

+-----+----------+------------+-----+
| id  | sales_id | product_id | qty |
+-----+----------+------------+-----+
| 517 |      211 |          1 | 200 |
+-----+----------+------------+-----+
| 518 |      211 |          1 | 120 |
+-----+----------+------------+-----+

生产

+----+------------+-------+
| id | product_id | qty   |
+----+------------+-------+
|  1 |          1 |    20 |
|  2 |          2 |   200 |
|  3 |          1 |    20 |
|  4 |          3 |    30 |
|  5 |          9 |    30 |
|  6 |         65 |    10 |
|  7 |         65 |    50 |
|  8 |         71 |    10 |
|  9 |         71 |    10 |
| 10 |         71 |    10 |
+----+------------+-------+

现在我正在创建具有相同表格定义的多个数据库,并且需要维护库存

将从单个数据库维护

生产表和产品表 只有 sales_item_details 表格不同,但产品ID相同

那么查询如何获得销售项目详细信息的SUM(数量)并查看库存中的库存

我试过这个:

SELECT
        `pr`.`id`,
        `pr`.`name`,
        sl.size,
        IFNULL(SUM(s.qty), 0) AS sales,
        IFNULL((SELECT SUM(qty) FROM production st WHERE st.product_id = `pr`.`product-id`), 0) AS stock_added
    FROM products pr
        LEFT JOIN (
            SELECT qty, product_id FROM db1.sales_item_details
            UNION ALL 
            SELECT qty, product_id FROM db2.sales_item_details 
        ) s ON pr.`id` = s.product_id
        LEFT JOIN size_list sl ON sl.id = `pr`.`product-size`
    GROUP BY s.product_id
    ORDER BY sales DESC

但获得销售的产品

任何帮助都会受到欢迎

1 个答案:

答案 0 :(得分:0)

首先,我在主数据库中创建了一个视图,其中包含按产品ID分组的所有销售项目:

CREATE OR REPLACE VIEW unit_sold_all  AS
    SELECT 
        p.`product-id` AS product_id,
        (
            (SELECT IFNULL(SUM(s0.qty), 0) FROM db_1.sales_item_details s0 WHERE s0.product_id = p.`product-id`) + 
            (SELECT IFNULL(SUM(s1.qty), 0) FROM db_2.sales_item_details s1 WHERE s1.product_id = p.`product-id`) + 
            (SELECT IFNULL(SUM(s2.qty), 0) FROM db_3.sales_item_details s2 WHERE s2.product_id = p.`product-id`) + 
            (SELECT IFNULL(SUM(s3.qty), 0) FROM db_4.sales_item_details s3 WHERE s3.product_id = p.`product-id`) + 
            (SELECT IFNULL(SUM(s4.qty), 0) FROM db_5.sales_item_details s4 WHERE s4.product_id = p.`product-id`) 
        ) as total_unit_sales
FROM products p

然后在另一个sql中,我选择了销售额的总和。

PS:我自己回答了这个问题,因为将来其他人可能需要。