2011-06-22 24 views
0

我有3個表末創建10條記錄從所有3代表的

表1

Primary_key int 
Forign_key int 
PostId 
CreatedDate Datetime 

表2

Primary_key int 
Forign_key int 
LocationId 
CreatedDate Datetime 

表3

Primary_key int 
Forign_key int 
UserId 
OrganisationId 
CreatedDate Datetime 

如何從所有3個表中選擇最新創建的10條記錄。 注意,3個表有不同的結構

SQL Server 2005中

+0

你想要輸出看起來像什麼? – gbn

+0

我的意思是30行或10行?什麼專欄? – gbn

回答

2

如果你想 「每桌最後10」

SELECT 
    * 
FROM 
    (
    SELECT 
     Primary_key, Forign_key, 
     UserId, OrganisationId, NULL AS LocationId, NULL AS PostID, 
     CreatedDate, 'table3' AS Source, 
     ROW_NUMBER() OVER (ORDER BY CreatedDate DESC) AS rn 
    FROM table3 
    UNION ALL 
    SELECT 
     Primary_key, Forign_key, 
     NULL, NULL, LocationId, NULL, 
     CreatedDate, 'table2', 
     ROW_NUMBER() OVER (ORDER BY CreatedDate DESC) AS rn 
    FROM table2 
    UNION ALL 
    SELECT 
     Primary_key, Forign_key, 
     NULL, NULL, NULL, PostID, 
     CreatedDate, 'table1', 
     ROW_NUMBER() OVER (ORDER BY CreatedDate DESC) AS rn 
    FROM table 
    ) T 
WHERE 
    t.rn <= 10 

對於 「最後的10比所有表」

SELECT TOP 10 
    * 
FROM 
    (
    SELECT 
     Primary_key, Forign_key, 
     UserId, OrganisationId, NULL AS LocationId, NULL AS PostID, 
     CreatedDate, 'table3' AS Source 
    FROM table3 
    UNION ALL 
    SELECT 
     Primary_key, Forign_key, 
     NULL, NULL, LocationId, NULL, 
     CreatedDate, 'table2' 
    FROM table2 
    UNION ALL 
    SELECT 
     Primary_key, Forign_key, 
     NULL, NULL, NULL, PostID, 
     CreatedDate, 'table1' 
    FROM table 
    ) T 
ORDER BY 
    CreatedDate DESC 
+0

我只需要10個,不是每桌。 10個最新記錄不是每張表 –

+0

@ user444569:我更新了我的答案 – gbn