2011-02-02 61 views
0

我有一个表中的3列说测试与列说col1,col2,col3,他们是一个sigle表的外键说test_master ...如何编写查询从test_master desc专栏为那些col1,col2,col3在测试中。SQL连接问题

例如

test table 
col1 col2 col3 
100 101 102 

test_master table 
id desc 
100 testdata1 
101 testdata1 
102 testdata1 
103 testdata1 

帮助,请...

回答

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 
+0

感谢您的答复... – soorajthomas 2011-02-02 13:28:02

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); 
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