简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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