简体   繁体   English

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

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

My database has two tables, one containing information about users and one containing a list of transactions between users.我的数据库有两个表,一个包含有关用户的信息,另一个包含用户之间的事务列表。 I want to select rows in the second table substituting the email with the username.我想在第二个表中用用户名替换 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
------------------------------------------------------

What I tried to do is using JOIN and UNION using the following query:我试图做的是使用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

Of course it doesn't work, instead returns:当然它不起作用,而是返回:

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

My question is, how do you join specific fields of two different tables, selecting rows in the second table on the basis of the value of a column?我的问题是,如何连接两个不同表的特定字段,根据列的值选择第二个表中的行? Thanks!谢谢!

PS: I know this question probably has an answer somewhere in the internet, but I already tried several solutions and none worked. PS:我知道这个问题可能在互联网的某个地方有答案,但我已经尝试了几种解决方案,但都没有奏效。

One solution would be to JOIN the accounts table twice, once for the sender and once for the receiver:一种解决方案是将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