2013-12-19 58 views
0

那還有例如:如何讓選擇與依賴於現有的額外列

select * from table 

,並得到

ID | NAME | MAIL    | BOSS_ID | 
1 | Mike | [email protected] | 2  | 
2 | Josh | [email protected] | null | 

我真正想要做的就是SELECT語句(不知何故?)顯示像兩列:

ID | NAME | MAIL    | BOSS_ID | BOSS_NAME | BOSS_MAIL 
1 | Mike | [email protected] | 2  | Josh  | [email protected] 
2 | Josh | [email protected] | null | null  | null 

我知道這看起來很傻,但我到底有沒有被要求做... 所有提示都非常感謝!

+0

http://www.w3schools.com/sql/sql_join.asp –

+0

您是否有另一張帶有Boss信息的表?即BOSS_ID,BOSS_NAME,BOSS_MAIL 如果是這樣,上面的評論應該讓你是你想要的,因爲這將加入BOSS_ID – shadowjfaith

回答

0

您不能選擇不存在的列。您需要添加它們。您希望ALTER TABLE語句是這樣的:

ALTER TABLE yourtable ADD BOSS_NAME VARCHAR(255) 
3

你做一個外連接表本身IDBOSS_ID

SQL Fiddle

MS SQL Server 2012的架構設置

create table YourTable 
(
    ID int, 
    Name varchar(10), 
    Mail varchar(20), 
    BOSS_ID int 
) 
insert into YourTable values 
(1 , 'Mike' , '[email protected]' , 2), 
(2 , 'Josh' , '[email protected]' , null) 

查詢1

select T1.ID, 
     T1.Name, 
     T1.Mail, 
     T2.Name as BossName, 
     T2.Mail as BossMail 
from YourTable as T1 
    left outer join YourTable as T2 
    on T1.BOSS_ID = T2.ID 

Results

| ID | NAME |    MAIL | BOSSNAME |   BOSSMAIL | 
|----|------|------------------|----------|------------------| 
| 1 | Mike | [email protected] |  Josh | [email protected] | 
| 2 | Josh | [email protected] | (null) |   (null) | 
+0

+1好的答案,我沒有考慮ID和BOSS_ID是相同的標識符。 – shadowjfaith

+0

好主意,但我仍然不得不使用臨時表......因爲如果我想嘗試: SELECT * FROM (一些select語句)爲T1 LEFT OUTER JOIN T1爲T2 ON T1.BOSS_ID = T2。 ID 它不會工作:( – user1421819