最后从3个表中创建了10条记录

时间:2011-06-22 09:55:52

标签: tsql

我有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

1 个答案:

答案 0 :(得分: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