MySQL-连接两个不同表的特定列

时间:2019-09-28 14:24:19

标签: mysql sql join select union

我的数据库有两个表,一个表包含有关用户的信息,另一个表包含用户之间的事务列表。我想在第二个表中选择行,用用户名替换电子邮件。

ACCOUNTS
----------------------------------------------
     email      | password | username | token
----------------------------------------------
 joe@mail.com   | xxxxxxxx | joe      | abcde
----------------------------------------------
 bob@mail.com   | xxxxxxxx | bob      | edcba
----------------------------------------------

TRANSACTIONS
------------------------------------------------------
     sender     |   receiver   | amount   | timestamp
------------------------------------------------------
 joe@mail.com   | bob@mail.com | 20       | 123456789
------------------------------------------------------

EXPECTED RESULT
------------------------------------------------------
     sender     |   receiver   | amount   | timestamp
------------------------------------------------------
 joe            | bob          | 20       | 123456789
------------------------------------------------------

我试图做的是使用JOINUNION并使用以下查询:

SELECT amount, timestamp, accounts.username AS sender, accounts.username FROM tx JOIN accounts ON sender=accounts.email 
UNION 
SELECT amount, timestamp, accounts.username AS receiver, accounts.username FROM tx JOIN accounts ON receiver=accounts.email

当然不起作用,而是返回:

-----------------------------------------------------
     sender     |   receiver   | amount   | timestamp
-----------------------------------------------------
 joe            | joe          | 20       | 123456789
-----------------------------------------------------
 bob            | bob          | 20       | 123456789
-----------------------------------------------------

我的问题是,如何连接两个不同表的特定字段,并根据列的值在第二个表中选择行?谢谢!

P.S:我知道这个问题可能在互联网上某个地方有答案,但是我已经尝试了几种解决方案,但没有一个可行。

1 个答案:

答案 0 :(得分:1)

一种解决方案是两次JOIN accounts表,一次是发送方,一次是接收方:

SELECT
    c1.username sender,
    c2.username receiver,
    t.amount,
    t.timestamp
FROM transactions t
INNER JOIN accounts c1 ON c1.email = t.sender
INNER JOIN accounts c2 ON c2.email = t.receiver