0

当我执行以下代码时,我得到的结果如下:

ID  column1 column2 

34  NULL    NULL
34  Org13   Org13
36  NULL    NULL
36  NULL    Org2
36  Org4    NULL
41  NULL    NULL
41  NULL    Org5
41  Org3    NULL

我希望我的结果看起来像:

ID  column1  column2

34  Org13   Org13
36  Org4    Org2
41  Org3    Org5

我有两张桌子:Table1 和 Table2。Table2 是一个查找表,包含以下字段:id、name

表 1 具有以下字段(id、column1、column2)。column1 和 column2 都与查找表有外键关系:

FK_1: Table1.column1-Table2.id
FK_2: Table1.column2-Table2.id

由于我想提取 column1 和 column2 的值,并且由于这两个值都是在同一字段(Table2.name)上的查找,我怀疑我需要进行内部选择。

我的代码如下。我该如何更改它以产生所需的结果,而不是我得到的结果?提前致谢!

DECLARE @value INT
SET @value = 14

SELECT DISTINCT 
    Table1.[id]         AS ID
    , ( SELECT DISTINCT
            Table2.[name] 
        WHERE 
            Table1.column1 =
            Table2.id ) AS column1
    , ( SELECT DISTINCT
            Table2.[name] 
        WHERE 
            Table1.column2 =
            Table2.id ) AS column2
FROM 
    Table1
    ,Table2
WHERE   
    Table1.[id] = @value
4

3 回答 3

3
    /*
    create table table1(id int, col1 int, col2 int);
    create table table2(id int, name varchar(10) );

    insert into table2 values(1, 'org 1');
    insert into table2 values(2, 'org 2');
    insert into table2 values(3, 'org 3');
    insert into table2 values(4, 'org 4');

    insert into table1 values(1, 1, 2);
    insert into table1 values(2, 2, 2);
    insert into table1 values(3, 2, 3);
    insert into table1 values(4, 4, 1);
    */

    select
        a.id,
        b.name as column1,
        c.name as column2
    from
         table1 a
    join table2 b on b.id = a.col1
    join table2 c on c.id = a.col2;


 id     column1     column2    
 -----  ----------  ---------- 
 1      org 1       org 2      
 2      org 2       org 2      
 3      org 2       org 3      
 4      org 4       org 1      

 4 record(s) selected [Fetch MetaData: 3/ms] [Fetch Data: 0/ms] 

 [Executed: 7/7/09 4:07:25 PM EDT ] [Execution: 1/ms]
于 2009-07-07T20:08:05.667 回答
2
DECLARE @value INT
SET @value = 14

SELECT
    t1.[id]                 AS ID
    MAX(t2a.name),
    MAX(t2b.name)
FROM 
    Table1 t1
    LEFT JOIN
    Table2 t2a ON t1.column1 = t2a.id
    LEFT JOIN
    Table2 t2b ON t1.column2 = t2b.id
WHERE   
    t1.[id] = @value
GROUP BY    
    t1.[id]    
于 2009-07-07T19:51:19.943 回答
2

gbn,我想你的意思是写

DECLARE @value INT
SET @value = 1

SELECT --??? DISTINCT 
    t1.[id] AS ID, --- missed comma
    table2a.name,
    table2b.name
FROM 
   Table1 t1
     JOIN Table2 table2a ON t1.column1 = table2a.id
     JOIN Table2 table2b ON t1.column2 = table2b.id -- you have t1.column1 oops
WHERE   
    t1.[id] = @value
于 2009-07-07T20:09:39.547 回答