繁体   English   中英

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

[英]MySQL - Join specific columns of two different tables

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

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
-----------------------------------------------------

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

PS:我知道这个问题可能在互联网的某个地方有答案,但我已经尝试了几种解决方案,但都没有奏效。

一种解决方案是将accountsJOIN两次,一次用于发送方,一次用于接收方:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM