MySQL选择库存管理查询

时间:2017-05-23 12:13:20

标签: php mysql database

我试图从购买和销售表中获取当前库存,但只获得一个结果。

这是我写的查询。

SELECT `I`.`id`, `I`.`modal`, `I`.`brand`, 
IFNULL(SUM(P.qty), 0) as p_qty, 
IFNULL(SUM(S.qty), 0) as s_qty, 
SUM(P.qty)-SUM(S.qty) as t_qty 
FROM `items` `I` 
    LEFT JOIN `purchase_details` `P` ON `P`.`item_id` = `I`.`id` 
    LEFT JOIN `sale_details` `S` ON `S`.`item_id` = `I`.`id` 
WHERE `I`.`id`
IN("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70") 
GROUP BY `P`.`item_id`

预期结果:所有项目应根据库存有或没有零。

2 个答案:

答案 0 :(得分:1)

尝试GROUP BY I.id

    SELECT
    `I`.`id`,
    `I`.`modal`,
    `I`.`brand`,
    IFNULL(SUM(P.qty),
    0) AS p_qty,
    IFNULL(SUM(S.qty),
    0) AS s_qty,
    SUM(P.qty) - SUM(S.qty) AS t_qty
FROM
    `items` `I`
LEFT JOIN
    `purchase_details` `P`
ON
    `P`.`item_id` = `I`.`id`
LEFT JOIN
    `sale_details` `S`
ON
    `S`.`item_id` = `I`.`id`
WHERE
    `I`.`id` IN(
        "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70"
    )
GROUP BY
    `I`.`id`

答案 1 :(得分:0)

试试这个

SELECT
    `I`.`id`,
    `I`.`modal`,
    `I`.`brand`,
    IFNULL((SELECT SUM(P.qty) FROM purchase_details `P` WHERE p.item_id = I.id),
    0) AS p_qty,
    IFNULL(SUM(S.qty),
    0) AS s_qty
FROM `items` `I`
LEFT JOIN `sale_details` `S` ON `S`.`item_id` = `I`.`id`
WHERE  `I`.`id`  BETWEEN 1 AND 70
GROUP BY I.id