我有这个查询
SELECT
currency_code,
SUM(CASE WHEN TYPE = 'buy'THEN to_amount END ) AS BUY,
SUM(CASE WHEN TYPE = 'sell' THEN to_amount END ) AS SELL,
SUM(CASE WHEN TYPE = 'sell' THEN rate END ) AS SELL_RATE,
SUM(CASE WHEN TYPE = 'buy' THEN rate END ) AS BUY_RATE,
AVG(CASE WHEN TYPE = 'buy' THEN rate END ) AS AVG_BUY_RATE,
AVG(CASE WHEN TYPE = 'sell' THEN rate END ) AS AVG_SELL_RATE
FROM tb_currency
LEFT JOIN tb_bill
ON tb_currency.CURRENCY_ID = tb_bill.CURRENCY_ID
AND tb_bill.TYPE IN ('buy', 'sell')
AND date( DATE_TIME ) >= '2011-01-01'
AND date( DATE_TIME ) <= '2011-01-11'
GROUP BY currency_code
将输出:
现在我想将此查询与另一个名为 tb_user
的表联系起来tb_user的PK名为 user_id ,上面查询中使用的 tb_bill 也有外键名为 user_id
tb_user
user_id (pk)| user_name | branch_id
tb_bill
bill_id (pk) | user_id (fk)|
期望的结果应该是上面的图片加上一列branch_id。 如果它没有branch_id,则返回null。
我尝试过几次但仍无法正确加入。希望你们能帮忙。
感谢。
答案 0 :(得分:1)
将user_id添加到SELECT部分 之后
LEFT JOIN tb_bill ON tb_currency.CURRENCY_ID = tb_bill.CURRENCY_ID
地方
LEFT JOIN tb_user ON tb_user.id = tb_bill.user_id
你也错过了WHERE(首先放置AND) 和
GROUP BY currency_code, user_id
答案 1 :(得分:1)
连接中的三个条件(AND子句)可能会给您带来麻烦。这三个条件是选择标准,而不是加入标准。
另外,你对CASE的使用对我来说很奇怪。我确信它有效,但IF可能更适合单条件函数。在下面,如果字段是浮点而不是整数,则将0替换为0.0。
SELECT currency_code,
SUM(IF(TYPE = 'buy', to_amount, 0)) AS BUY,
SUM(IF(TYPE = 'sell', to_amount, 0)) AS SELL,
SUM(IF(TYPE = 'sell', rate, 0)) AS SELL_RATE,
SUM(IF(TYPE = 'buy', rate, 0)) AS BUY_RATE,
AVG(IF(TYPE = 'buy', rate, 0)) AS AVG_BUY_RATE,
AVG(IF(TYPE = 'sell', rate, 0)) AS AVG_SELL_RATE,
tb_user.whatever_field,
tb_user.whatever_other_field
FROM tb_currency
LEFT JOIN tb_bill ON tb_currency.CURRENCY_ID = tb_bill.CURRENCY_ID
LEFT JOIN tb_user ON tb_bill.user_id = tb_user.user_id
WHERE tb_bill.TYPE IN ('buy', 'sell')
AND date( DATE_TIME ) >= '2011-01-01'
AND date( DATE_TIME ) <= '2011-01-11'
GROUP BY currency_code, tb_user.user_id
最后,全局字段名称看起来也很奇怪。无论什么对你有用。