簡體   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