如何使用MySQL连接两个表多个字段?

时间:2016-03-16 03:40:48

标签: mysql

我正在尝试连接两个包含多列的表。

用户

id | user_id |的 ACCOUNT_ID

平衡

id | receiver_account | sender_account |量

用户表account_id将位于balance_account字段或余额表中 sender_account字段。所以我想加入用户account_id 余额表的recevier_account字段或sender_account字段。

如果我这样做是正确的,

SELECT *
FROM users
JOIN balance ON balance.receiver_account = users.account_id
        OR
        balance.sender_account = users.account_id

2 个答案:

答案 0 :(得分:0)

不,请改为:

SELECT * 
FROM balance b LEFT JOIN users receiver ON b.receiver_account = receiver.account_id
LEFT JOIN users sender ON b.sender_account = sender.account_id

答案 1 :(得分:0)

试试这个

Select s.id, s.user_id, s.account_id, b.id, b.receiver_account , b.sender_account , b.amount 
from users s 
inner join balance b on s.account_id = b.account_id
or
b.sender_account = s.account_id