左连接复杂的SQL查询

时间:2011-01-10 05:57:38

标签: mysql left-join

大家好我有这个问题

SELECT currency_code, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
END ) AS cash_in, SUM(
CASE
WHEN TYPE = 'cash_out'
THEN amount
END ) AS cash_out, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
ELSE - amount
END ) AS balance
FROM tb_cash_transaction
LEFT JOIN tb_currency ON tb_currency.CURRENCY_ID = tb_cash_transaction.CURRENCY_ID
WHERE TYPE IN (
'cash_in', 'cash_out'
)
GROUP BY currency_code

这将输出:

alt text

问题是查询不显示另一个currency_code KRW,它在tb_cash_transaction中没有数据。 tb_currency中的示例

alt text

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT currency_code, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
END ) AS cash_in, SUM(
CASE
WHEN TYPE = 'cash_out'
THEN amount
END ) AS cash_out, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
ELSE - amount
END ) AS balance
FROM tb_currency 
LEFT JOIN tb_cash_transaction ON tb_currency.CURRENCY_ID = tb_cash_transaction.CURRENCY_ID AND tb_cash_transaction.TYPE IN (
'cash_in', 'cash_out'
)
GROUP BY currency_code