SQL中能否对两张表通过多列执行INNER JOIN?附账户转账表关联查询问题
错误原因
两次关联accounts表时未设置不同别名,数据库无法区分重复的字段归属,导致语句运行失败。
正确写法
SELECT t.transferID, t.wherefrom, from_acc.accountName AS from_account_name, from_acc.balance AS from_account_balance, t.whereto, to_acc.accountName AS to_account_name, to_acc.balance AS to_account_balance, t.amount, t.time FROM transfer t INNER JOIN accounts from_acc ON t.wherefrom = from_acc.accountID INNER JOIN accounts to_acc ON t.whereto = to_acc.accountID ORDER BY t.time DESC;
补充说明
- 给
transfer表取别名t,accounts表分别取别名from_acc(对应转出账户)、to_acc(对应转入账户),避免表名重复冲突 - 查询字段前明确标注所属表别名,避免出现字段歧义,你也可以根据实际需求增减要查询的字段
内容的提问来源于stack exchange,提问作者Patrik Vörös
相关产品推荐
相关产品推荐

