我有2个表,t1和t2,t1保存别名和分数,而t2保存别名及其真实姓名,我希望构建一个查询以获取分数,真实姓名和别名(示例-所需结果)>
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
所需结果
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
当前结果
以下查询为我提供了查询中t2.name的所有实例的tl_name,我认为该查询是正确的,但是我想拥有的是,t2.name的第一个实例应显示user_name,然后下一个实例应显示tl_name,然后显示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
以下内容也不起作用
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
答案 0 :(得分:1)
使用内部联接和子查询
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
或通过使用表别名将与t2的连接使用两次
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
答案 1 :(得分:0)
我在最初的评论中打错了口号,实际上您需要加入t2 3 次,就像这样...
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
;