【发布时间】:2020-01-28 12:43:23
【问题描述】:
我的数据库有两张表,一张包含有关用户的信息,另一张包含用户之间的交易列表。我想在第二个表中选择行,用用户名替换电子邮件。
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
------------------------------------------------------
我尝试使用JOIN 和UNION 使用以下查询:
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:我知道这个问题可能在互联网的某个地方有答案,但我已经尝试了几种解决方案,但都没有奏效。
【问题讨论】:
标签: mysql sql join select union