[英]Combine two MySQL queries to one
Is it possible to combine these two queries into one query? 是否可以将这两个查询合并为一个查询?
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';
so I get the result: 所以我得到了结果:
| credit | debit |
| 90 | 60 |
use CASE
in your SELECT
clause 在SELECT
子句中使用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';
Use like this. 像这样使用。
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 answered if this answer answers your question... - Mark回答了这个答案是否回答了你的问题......
Thank you for your help. 谢谢您的帮助。 This is how I used it in Zend framework: 这是我在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 ...... ");
}
尝试这个
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.