简体   繁体   中英

Mysql query to get data from multiple tables

I have 2 tables, t1 and t2, t1 holds aliases and scores, while t2 holds aliases and their real names, I wish to build a query to get the scores,real names and aliases (example - desired results)

t1

alias - scores - tl_alias - tm_alias (column names)

tk - 96 - pp - jj
sp - 94 - pp - jj

t2

name - alias - role  (column names)

tom Koshy - tk - user  
shaun penn - sp - user  
peter pan - pp - tl  
john james - jj - tm

Desired Result

user_alias - user_name - scores - tl_alias - tl_name - tm_alias - tm_name (column labels)


tk - tom koshy - 96 - pp - peter pan - jj - john james
sp - shaun penn - 94 - pp - peter pan - jj - john james

Current Results

The below query gives me tl_name for all instances of t2.name in the query which I think is correct as per the query but what I would like to have is, the first instance of t2.name should show the user_name, then next instance should show the tl_name and then the tm_name

SELECT t1.alias,t2.name,t1.scores,t1.tl_alias,t2.name,t1.tm_alias,t2.name from t1 JOIN t2 on t1.tl_alias = t2.alias

tk - peter pan - 96 - pp - peter pan - jj - peter pan
sp - peter pan - 94 - pp - peter pan - jj - peter pan

The below does not work either

SELECT t1.alias,t2.name,t1.scores,t1.tl_alias,t2.name,t1.tm_alias,t2.name from t1 JOIN t2 on t1.tl_alias = t2.alias, t1.tm_alias = t2.alias

use inner join and sub-query

select t3.*,t2.name  from
(    
 select t1.alias,t2.name, t1.scores ,t1.tl_alias  from t1 join t2 on t1.alias =t2.alias
) as t3 join t2 on t3.tl_alias  =t2.tl_alias  

or use join with t2 for two times by using table alias

select t1.alias,t2.name, t1.scores ,t1.tl_alias,t3.name 
 from t1 join t2 on t1.alias =t2.alias
      join t2 as t3 on t1.tl_alias=t3.alias

I misspoke in my initial comment, you actually need to join to t2 three times, like so...

SELECT t1.alias AS user_alias, t2_u.name AS user_name
   , t1.scores
   , t1.tl_alias, t2_l.name AS tl_name
   , t1.tm_alias, t2_m.name AS tm_name
FROM t1 
   JOIN t2 AS t2_u on t1.alias = t2_u.alias
   JOIN t2 AS t2_l on t1.tl_alias = t2_l.alias
   JOIN t2 AS t2_m ON t1.tm_alias = t2_m.alias
;

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