将两个MySQL查询合并为一个

时间:2012-10-17 09:26:15

标签: mysql

是否可以将这两个查询合并为一个查询?

SELECT sum(amount) as credit FROM statement WHERE userId= '33003' AND debitOrCredit = '1' AND actionDate <= '2012-10-17';

SELECT sum(amount) as debit FROM statement WHERE userId= '33003' AND debitOrCredit = '0' AND actionDate <= '2012-10-17';

所以我得到了结果:

| credit  | debit  |   
|   90    |   60   |

5 个答案:

答案 0 :(得分:3)

您可以在SUM中使用CASE

SELECT sum(CASE WHEN debitOrCredit = '1' THEN amount ELSE 0 END) as credit,
       sum(CASE WHEN debitOrCredit = '0' THEN amount ELSE 0 END) as debit
FROM statement WHERE userId= '33003' AND actionDate <= '2012-10-17';

答案 1 :(得分:2)

CASE子句中使用SELECT

SELECT sum(CASE WHEN debitOrCredit = '1' THEN amount ELSE 0 END) as credit,
       sum(CASE WHEN debitOrCredit = '0' THEN amount ELSE 0 END) as debit
FROM   statement 
WHERE  userId= '33003'  AND 
       actionDate <= '2012-10-17';

答案 2 :(得分:0)

像这样使用。

SELECT sum(a.amount) as credit,sum(b.amount) as debit FROM statement a left join statement b
on a.userId=b.userId
 WHERE a.userId= '33003' AND a.debitOrCredit = '1' AND b.debitOrCredit = '0' AND a.actionDate <= '2012-10-17' AND b.actionDate <= '2012-10-17' ;

- Mark回答了这个答案是否回答了你的问题......

答案 3 :(得分:0)

感谢您的帮助。 这就是我在Zend框架中使用它的方式:

$sql = $this->_dba->select()
    ->from('statement', array(
        "credit" => "sum(CASE WHEN debitOrCredit = '1' THEN amount ELSE 0 END)",
        "debit" => "sum(CASE WHEN debitOrCredit = '0' THEN amount ELSE 0 END)"))
    ->where('userId = ?', $userId)
    ->where('actionDate <= ?', $date);

    try
    {
        $result = $this->db->fetchRow($sql);
        //process result here       
    }
    catch (Exception $e)
    {
        throw new Exception("Error on ...... ");
    }

答案 4 :(得分:-1)

试试这个

SELECT sum(case when debitOrCredit = '1' then amount else 0 end) as credit, sum(case when debitOrCredit = '2' then amount else 0 end) as debit FROM statement WHERE userId= '33003' AND actionDate <= '2012-10-17'