2014-02-06 189 views
1

我做了兩個表:一個5列,另一個3列。 通過使用左外連接,我希望我的結果表顯示第一個表的所有5列以及第二個表的第一列。任何解決方案 它顯示第二張表的所有3列,但我希望它只顯示一個。左外部連接sql 2012

+0

後查詢。瘋狂的猜測是,當你應該在'SELECT'列表中指定列時,你正在使用'SELECT *'。 –

+0

是的,我正在使用select *。我應該命名選擇語句中的所有列? – Smith

+1

你應該命名你想要返回的。 'SELECT *'方便原型設計,但通常不應用於生產代碼。 'SELECT t1.col1,t1.col2,t1.col5,t2.col1 FROM t1 LEFT JOIN t2 ....' –

回答

1

SELECT *始終顯示全部來自查詢中所有表的列。

如果你想要這些的一個子集,你必須更具體。例如:

SELECT t1.*, t2.column1 
FROM t1 
LEFT OUTER JOIN t2 ... 
+0

使用*會給出錯誤,表示表名與此查詢中的任何列不匹配,可能是因爲我是在新的查詢中執行它。但提到每個列表名稱解決了問題。 – Smith

+0

這是我的學校作業,我被要求加入兩個表,因此您建議加入的最好方法是什麼? – Smith

+0

如果他們要求您使用左外連接,則使用左外連接。 –

1
SELECT T1.*, T2.FirstColumnName 
FROM T1 
LEFT OUTER JOIN T2 
    ON T1.Id = T2.Id 
1

試着這麼做:

create table dbo.Alpha 
(
    id int not null identity(1,1) primary key clustered , 
    A int not null , 
    B int not null , 
    C int not null , 
) 
create table dbo.Bravo 
(
    id  int not null identity(1,1) primary key clustered , 
    Alpha_ID int  null foreign key references dbo.Alpha(id) , 
    A  int not null , 
    B  int not null , 
    C  int not null , 
) 

select a.* , -- all colulmns from the first table 
     b.A , -- specific columns from the second table 
     b.B -- specific columns from the second table 
from  dbo.Alpha a 
left join dbo.Bravo b on b.Alpha_ID = a.id