形成sql查询

bhmjp9jg  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(205)

我真的希望您能帮助我形成一个sql查询,它可以执行以下操作:
我有两张table

Pages 
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Key] [nvarchar](450) NULL,
    [CreatedAt] [datetimeoffset](7) NOT NULL,
    [Title] [nvarchar](max) NULL
)

Contents 
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [PageId] [int] NULL,
    [Key] [nvarchar](450) NULL,
    [Version] [int] NOT NULL,
    [Text] [nvarchar](max) NULL
)

Id |   Key   | CreatedAt | Title
---+---------+-----------+-------
 1 | "page1" | 20200101  | ....

Id | PageId |   Key  | Version | Text 
---+--------+--------+---------+------
 1 |    1   | "key1" |    1    | .....
 2 |    1   | "key1" |    2    | .....
 3 |    1   | "key2" |    1    | .....
 4 |    1   | "key2" |    2    | .....
 5 |    1   | "key3" |    1    | .....

我有兴趣得到的网页和每个内容的最新版本在哪里 PageId 与页面匹配。

更新

key是传递以获得结果的键

Select * from Pages where [Key] = 'the key of the page'

期望的结果是

Page.Id | Page.Key | Page.CreatedAt | Page.Title | Content.Id | Content.PageId | Content.Key | Content.Version | Content.Text
---------------------------------------------------------------------------------------------------------------------------------
   1    |  "Page1" |    20200101    |   ......   |     2      |        1       |    "Key1"     |    2     | ......
   1    |  "Page1" |    20200101    |   ......   |     4      |        1       |    "Key2"     |    2     | ......
   1    |  "Page1" |    20200101    |   ......   |     5      |        1       |    "Key3"     |    1     | ......
6tdlim6h

6tdlim6h1#

我们需要更多信息。要获得最新的结果,您可以对输出进行排序,并限制结果的数量,如下所示:

SELECT PageID FROM Contents WHERE PageID=$pageid ORDER BY id DESC LIMIT 3
eni9jsuy

eni9jsuy2#

如果你所说的最新版本是指最高版本,那么你可以使用 ROW_NUMBER() 窗口功能:

select p.*, c.* 
from Pages p 
left join (
  select *, row_number() over (partition by PageId, [Key] order by version desc) rn
  from Contents
) c on c.PageId = p.Id and c.rn = 1

请看演示。

相关问题