当我执行以下代码时,我得到的结果如下:
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
Table1具有以下字段(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
答案 0 :(得分: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]
答案 1 :(得分: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]
答案 2 :(得分:2)
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