我有三张桌子:
1. user => user_id[Pk], user_name
2. payment => payment_id[PK], user_id[FK], amount
3. receive => receive_id[PK], user_id[FK], amount
现在我想获取像:
这样的记录用户名,paymentamount,receivableamount
提前致谢..
我已阅读this,但它对我不起作用。
假设,在用户表
中 USER_ID USER_NAME
1 ABC
2 XYZ
在付款表
中 payment_id USER_ID量
1个1 1000
2个1 200
3个2 150
在接收表中:
receive_id USER_ID量
1个2 100
2 1 200
现在我想要像
这样的记录 USER_NAME paymentamount receivableamount
ABC 1000 200
ABC 200
XYZ 150 100
答案 0 :(得分:2)
您可能希望按user_id汇总金额。
SELECT
user.user_id,
SUM(payment.amount) AS payment_amount,
SUM(receive.amount) AS receive_amount
FROM (receive INNER JOIN [user] ON receive.user_id = user.user_id)
INNER JOIN payment ON user.user_id = payment.user_id
GROUP BY user.user_id;
答案 1 :(得分:1)
使用内置查询设计器。将三个表拖入其中,链接键(将字段拖放到彼此),双击要将其添加到底部字段列表的字段,然后运行查询。如果需要,请选择聚合表达式。
答案 2 :(得分:0)
您可能需要根据MSAccess语法进行调整,但其目的是执行LEFT JOIN
付款并接收带有用户的表,因为这是父表,而其他两个表可能有也可能没有这个用户。
SELECT
u.user_name,
ISNULL(p.amount, 0) as paymentamount,
ISNULL(r.amount, 0) as receivableamount
FROM
user u
LEFT JOIN payment p
ON u.user_id = p.user_id
LEFT JOIN receive r
ON u.user_id = r.user_id
答案 3 :(得分:0)
select
user.user_name, payment.amount, receive.amount
from user
join payment on user.user_id == payment.user_id
join receive on user.user_id = receive.user_id;
答案 4 :(得分:0)
select t1.user_name, t2.amount payementamount, t3.amount receiveableamount from
User t1,
payment t2,
receive t3
where
t1.user_id=t2.user_id and
t1.user_id=t3.user_id
你可以尝试一下......