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

时间:2014-05-29 14:59:00

标签: mysql

我有一个包含以下列的数据库

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子句,但如果我删除它们,查询将永远运行

1 个答案:

答案 0 :(得分:0)

你需要使用另一个表格加入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

这是 demo

根据您的表名更改查询中的表名,它应该有效。

<强>更新 以下查询应该可以解决问题,您的查询非常混乱

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