剛有網友提問,只有一張表,其中有子鍵與父鍵關聯,怎樣根擾子鍵查詢到父鍵記錄的數據? Insus.NET嘗試寫了一個簡單的例子,希望能看得懂。 CREATE TABLE [dbo].[tempTable] ( [id] INT , [parent_id] INT NULL, [itemName] NV ...
剛有網友提問,只有一張表,其中有子鍵與父鍵關聯,怎樣根擾子鍵查詢到父鍵記錄的數據?
Insus.NET嘗試寫了一個簡單的例子,希望能看得懂。
CREATE TABLE [dbo].[tempTable] ( [id] INT , [parent_id] INT NULL, [itemName] NVARCHAR(40) ) GO INSERT INTO [dbo].[tempTable] ( [id], [parent_id], [itemName] ) VALUES (1,NULL,'a'), (2,NULL,'b'), (3,1,'c'), (4,NULL,'d'), (5,3,'e') GO SELECT [id],[parent_id],[itemName] FROM [dbo].[tempTable] GOSource Code
下麵是表關聯:
SELECT ta.[id] AS [子表id], tb.[id] AS [父表id], ta.[itemName] AS [子表name], tb.[itemName] AS [父表name] FROM [dbo].[tempTable] AS ta INNER JOIN [dbo].[tempTable] AS tb ON (ta.[parent_id] = tb.[id]) GOSource Code
後來網友提供數據,數據如下:
CREATE TABLE [dbo].[tempTable] ( [id] INT , [parent_id] INT NULL, [itemName] NVARCHAR(40) ) GO INSERT INTO [dbo].[tempTable] ( [id], [parent_id], [itemName] ) VALUES (1,0,'廣東省'), (2,1,'廣州市'), (3,2,'增城區'), (5,3,'小池鎮'), (8,5,'XX村'), (9,5,'YY村'), (10,5,'ZZ村') GO SELECT [id],[parent_id],[itemName] FROM [dbo].[tempTable] GOSource Code
Insus.NET寫的關聯語句及查詢語句:
SELECT ta.[id] AS [A-id], ta.[itemName] AS [A-name], tb.[id] AS [B-id], tb.[itemName] AS [B-name], tc.[id] AS [C-id], tc.[itemName] AS [C-name] , td.[id] AS [D-id], td.[itemName] AS [D-name] , te.[id] AS [E-id], te.[itemName] AS [E-name] FROM [dbo].[tempTable] AS te INNER JOIN [dbo].[tempTable] AS td ON (te.[parent_id] = td.[id]) INNER JOIN [dbo].[tempTable] AS tc ON (td.[parent_id] = tc.[id]) INNER JOIN [dbo].[tempTable] AS tb ON (tc.[parent_id] = tb.[id]) INNER JOIN [dbo].[tempTable] AS ta ON (tb.[parent_id] = ta.[id]) GOSource Code