简体   繁体   中英

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

I have a database with the folliwing column

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

And another table having the following column

account_id           rank
123                  4
124                  5
234                  1
235                  7

What i want is to get the following results

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

Please any help....

The query i tried is

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
)

it works well with where clauses but if i remove them the query runs forever

You need to use JOIN the another table 2 times something as

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

Here is a demo

Change the table names in the query as per your table name and it should work.

UPDATE The following query should do the trick, your query is pretty messed up

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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