我有一个表t1,其中有三列id,c1,c2,c3,带有一些数字。我有一个不同的表t2,其中包含id,name,其中id中的值是c1,c2,c3的值。
我无法编写查询,我可以将结果作为
id | c1的名字c2的名字c3的名字
有人可以提供帮助吗。
答案 0 :(得分:6)
一种方法是编写子查询以检索每列的名称:
select t1.id
, (select name from t2 where t2.id = t1.c1) as C1Name
, (select name from t2 where t2.id = t1.c2) as C2Name
, (select name from t2 where t2.id = t1.c3) as C3Name
from t1
或者你可以使用tripe join:
select t1.id
, t2_1.name as C1Name
, t2_2.name as C2Name
, t2_3.name as C3Name
from t1
join t2 as t2_1 on t1.c1 = t2_1.id
join t2 as t2_2 on t1.c2 = t2_2.id
join t2 as t2_3 on t1.c3 = t2_3.id
答案 1 :(得分:2)
您需要在每个值上加入三次以获取其名称。
SELECT T1.id, FirstJoin.Name, SecondJoin.Name, ThirdJoin.Name FROM T1
JOIN T2 FirstJoin On T1.c1 = FirstJoin.Id
JOIN T2 SecondJoinOn T1.c2 = SecondJoin.Id
JOIN T2 ThirdJoinOn T1.c3 = ThirdJoin.Id
我为蹩脚的走样道歉。
答案 2 :(得分:0)
SELECT
t1.id,
sub1.name,
sub2.name,
sub3.name
FROM
t1
JOIN t2 AS sub1 ON t1.c1 = sub1.id
JOIN t2 AS sub2 ON t1.c2 = sub2.id
JOIN t2 AS sub3 ON t1.c3 = sub3.id;
但你应该修复你的数据模型,3列具有相同类型的数据,听起来像一个糟糕的数据模型。做一些规范化。