[英]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 它与where子句很好地工作,但是如果我删除它们,查询将永远运行
You need to use JOIN the another table 2 times something as 您需要使用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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.