2011-02-02 14 views
0

私は3つのカラムを持っています。たとえば、col1、col2、col3という名前のテストは、sigleテーブルの外部キーです。test_master ... test_masterからdescカラムを取得する方法テストのcol1、col2、col3。sql join issueの問題

test table 
col1 col2 col3 
100 101 102 

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

助けてください...あなたがする必要がある

答えて

3

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

+0

私は上記の考えでは、我々は単一でそれを行うものとする参加? – soorajthomas

+0

問題ないですが、それがあなたに役立つかどうか教えてください。 – Blorgbeard

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