繁体   English   中英

通过从一个表中选择一个列两次来在mysql中连接两个表

[英]Joining two tables in mysql by selecting one colum twice from one table

我有一个带有愚蠢列的数据库

sender_account_id     receiver_account_id   date
123                   234                   2013-01-23
124                   235                   2012-04-04

另一个具有以下列的表

account_id           rank
123                  4
124                  5
234                  1
235                  7

我想要得到以下结果

sender_account_id   rank   receiver_account_id    rank
123                 4      234                    1
124                 5      235                    7

请任何帮助。

我试过的查询是

SELECT * 
FROM (

SELECT kudosent.sender_account_id, account.kudo_rank
FROM kudosent
INNER JOIN account ON kudosent.sender_account_id = account.account_id
WHERE kudosent.sender_account_id =337
) AS A
LEFT JOIN (

SELECT kudosent.sender_account_id AS b1id, kudosent.receiver_account_id, account.kudo_rank
FROM kudosent
INNER JOIN account ON kudosent.receiver_account_id = account.account_id
WHERE kudosent.sender_account_id =337
) AS B ON A.sender_account_id = B.B1id
UNION (

SELECT * 
FROM (

SELECT kudosent.sender_account_id, account.kudo_rank
FROM kudosent
INNER JOIN account ON kudosent.sender_account_id = account.account_id
WHERE kudosent.sender_account_id =337
) AS A
RIGHT JOIN (

SELECT kudosent.sender_account_id AS B2id, kudosent.receiver_account_id, account.kudo_rank
FROM kudosent
INNER JOIN account ON kudosent.receiver_account_id = account.account_id
WHERE kudosent.sender_account_id =337
) AS B ON A.sender_account_id = B.B2id
)

它与where子句很好地工作,但是如果我删除它们,查询将永远运行

您需要使用JOIN另一个表2次作为

select 
t1.sender_account_id,
t2.rank as sender_rank,
t1.receiver_account_id,
t3.rank as receiver_rank 
from table1 t1
join table2 t2 on t1.sender_account_id = t2.account_id 
join table2 t3 on t1.receiver_account_id = t3.account_id

这是一个演示

根据您的表名更改查询中的表名,它应该可以工作。

更新以下查询应该可以解决问题,您的查询很混乱

select 
t1.sender_account_id,
t2.rank as sender_rank,
t1.receiver_account_id,
t3.rank as receiver_rank 
from kudosent t1
join account t2 on t1.sender_account_id = t2.account_id 
join account t3 on t1.receiver_account_id = t3.account_id

暂无
暂无

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

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