1. 程式人生 > >簡單的單表自連線查詢

簡單的單表自連線查詢

insert into SayReply values ('其實我也不知道為啥不好','2017-04-21 11:34:43','曹操',3)
insert into SayReply values ('我知道心情為啥不好','2017-04-21 11:35:36','諸葛亮',1)
insert into SayReply values ('那你說說為啥不好','2017-04-21 11:35:49','曹操',6)

insert into SayReply values ('因為你家司馬懿不行了','2017-04-21 12:05:47','諸葛亮',7)
insert into SayReply values ('管我啥事','2017-04-21 12:06:18','司馬懿',8)
insert into SayReply values ('既生亮何生瑜','2017-04-21 13:38:21','周瑜',0)
insert into SayReply values ('經典說得好,周先生','2017-04-21 13:38:43','諸葛亮',10)

insert into SayReply values ('厲害了我的哥','2017-04-21 13:39:02','曹操',11)
insert into SayReply values ('亮啊,你別生周先生的氣','2017-04-21 13:40:46','司馬懿',10)
insert into SayReply values ('沒看懂','2017-04-21 13:41:12','粟裕',10)
insert into SayReply values ('別說話,小草','2017-04-21 13:41:59','諸葛亮',12)

--修改欄位型別
ALTER TABLE SayReply ALTER COLUMN Content Nvarchar(max);

--6.查詢司馬懿回覆的資訊
select * from SayReply where  Publisher='司馬懿';

--7連線查詢被“司馬懿”評論和回覆的資料,要求顯示被評論和回覆的內容和人名 及“司馬懿”評論和回覆的內容
select b.content as P_content,b.Publisher as P_person,b.releasetime as P_releasetime,a.content as C_content,a.Publisher as C_Person,a.releasetime as C_reseasetime from SayReply as a left join SayReply b on a.ParentID=b.id where a.Publisher='司馬懿'


--8.修正7題查詢結果,並定義別名
select (b.content+ ' 作者:'+b.Publisher) as '留言',(a.content+ ' 作者:' +a.Publisher)as '回覆內容' from SayReply as a left join SayReply b on a.ParentID=b.id where a.Publisher='司馬懿'

--9.修正7題查詢結果,並定義別名
 
select (two.Content +' 作者: '+two.Publisher) as 留言,(one.Publisher  +' 在:'+CONVERT(varchar(100),(one.Releasetime), 20)+'【評論】: '+two.Publisher+'說:'+one.Content) as 回覆內容 from SayReply as two inner join SayReply as one on one.ParentId=two.Id where one.Publisher='司馬懿'

 

 --10連線查詢所有的說說回覆資訊
with t as
(select t1.ParentID ,t1.id ,t1.Publisher person1 ,t2.Publisher person2 ,t1.content from SayReply t1 left join SayReply t2 on t1.ParentID=t2.id)
select case when t.ParentID = 0 then person1+'【釋出】:'+content
when t.ParentID in (select id from t where ParentID=0) then person1+'【評論】'+person2+'說:'+content
else person1 +'【回覆】'+person2+'說:'+content end
from t