我在表中有3列表示测试用列表示col1,col2,col3,它们是sigle表的外键说test_master ...如何编写查询以从test_master获取那些col1,col2的desc列, col3在测试中。
例如
test table
col1 col2 col3
100 101 102
test_master table
id desc
100 testdata1
101 testdata1
102 testdata1
103 testdata1
请帮助...
答案 0 :(得分:3)
您需要在同一张桌子上进行三次连接:
select tm1.desc, tm2.desc, tm3.desc
from test t
join test_master tm1 on t.col1=tm1.id
join test_master tm2 on t.col2=tm2.id
join test_master tm3 on t.col3=tm3.id
答案 1 :(得分:0)
我不确定你是否正在考虑让测试表中的每一列都是输出中的一行,或者你正在使用什么数据库,但你可以使用一个联合:
select t.col1, tm.desc from test t left outer join test_master tm on
(t.col1=tm.id)
union all
select t.col2, tm.desc from test t left outer join test_master tm on
(t.col2=tm.id)
union all
select t.col3, tm.desc from test t left outer join test_master tm on
(t.col3=tm.id);
答案 2 :(得分:0)
这可行,但可能效果不佳,具体取决于数据集的大小。
CREATE TABLE test
(col1 int, col2 int, col3 int)
INSERT INTO test
VALUES (101,102,103)
CREATE TABLE test_master
( id int, [desc] varchar(20))
INSERT INTO test_master
SELECT 100, 'testdata1'
UNION ALL SELECT 101, 'testdata1'
UNION ALL SELECT 102, 'testdata1'
UNION ALL SELECT 103, 'testdata1'
SELECT tm.id, [desc]
FROM test t
JOIN test_master tm ON tm.id IN (t.col1,t.col2,t.col3)
结果:
id desc
101 testdata1
102 testdata1
103 testdata1