根据mysql中的不同条件选择两列

时间:2011-12-02 15:16:12

标签: php mysql

<?php
    $inventory_in = $db->get_one("SELECT COALESCE(SUM(Qty), 0) 
                    FROM inventory Where id=12 AND inv_type = 'in' LIMIT 1");

    $inventory_out = $db->get_one("SELECT COALESCE(SUM(Qty), 0) 
                     FROM inventory Where id=12 AND inv_type = 'out' LIMIT 1");

    $inventory = $inventory_in - $inventory_out;
?>

可以将两个查询合并到一个中吗?

谢谢。

3 个答案:

答案 0 :(得分:2)

假设您想要两个值输出,您可以使用SUM / CASE

SELECT
      COALESCE(SUM(CASE WHEN inv_type = 'in' THEN Qty ELSE 0 END ), 0) as  Sum1,
      COALESCE(SUM(CASE WHEN inv_type = 'out' THEN Qty ELSE 0 END ), 0) as  Sum2
FROM inventory 
WHERE id=12 
LIMIT 1

您可能希望将and inv_type in ('in', 'out')添加到where子句中,但不是必需的。

答案 1 :(得分:0)

条件金额怎么样?

SELECT 
    SUM(CASE WHEN inv_type = 'in' THEN 1 ELSE 0 END) InSum
    SUM(CASE WHEN inv_type = 'out' THEN 1 ELSE 0 END) OutSum
WHERE
    id = 12

或者如果您只想要结果

SELECT 
    SUM(CASE inv_type WHEN 'in' THEN 1 WHEN 'out' THEN -1 ELSE 0 END) TotalSum
WHERE
    id = 12

答案 2 :(得分:0)

SELECT inv_type, COALESCE(SUM(Qty), 0) 
FROM inventory
WHERE id=12 AND inv_type IN ('in', 'out')
GROUP BY inv_type