简体   繁体   English

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

[英]select two columns base on different condition in 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;
?>

Possible to combine two queries into one ? 可以将两个查询合并为一个吗?

Thank you. 谢谢。

Assuming you want both values output you can use SUM/CASE 假设您想要两个值输出,您可以使用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

You may want to add and inv_type in ('in', 'out') to your where clause but its not required. 您可能希望将and inv_type in ('in', 'out')添加到where子句中,但不是必需的。

How about a conditional sum? 有条件的金额怎么样?

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

Or if you just want the result 或者,如果你只是想要结果

SELECT 
    SUM(CASE inv_type WHEN 'in' THEN 1 WHEN 'out' THEN -1 ELSE 0 END) TotalSum
WHERE
    id = 12
SELECT inv_type, COALESCE(SUM(Qty), 0) 
FROM inventory
WHERE id=12 AND inv_type IN ('in', 'out')
GROUP BY inv_type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM