仅select第一行又加入了table
Only select the first row from another joined table
我有两个 table:
Labs
==========
LabID
==========
1
Messages
==========
Message
==========
Hello world
Hello world 2
我想加入两个 table,所以输出变成:
=== Lab ID === Messages ===
1 Hello World
如果我这样做
select * from Labs l inner join Messages m on l.LabID = m.LabID
它打印出第一个 ID 两次,因为其中有两条消息 table。我只想select第一条消息。
我尝试添加 top 1 但这没有做任何事情。我真的是 SQL.
的新手
您似乎想要每个实验室的最新消息。一种选择是使用横向连接。假设 table messages
有一个名为 labid
的外键列引用 labs
,还有一个名为 id
的列可用于对行进行排序,你会这样表述:
select l.*, m.mesage
from labs l
cross apply (
select top (1) * from messages m where m.labid = l.labid order by m.id desc
) m
如果您想允许没有消息的实验室,请改用 outer apply
。
另一种选择是row_number()
:
select l.*, m.mesage
from labs l
inner join (
select m.*, row_number() over(partition by labid order by id desc) rn
from messages m
) m on m.labid = l.labid and m.rn = 1
我有两个 table:
Labs
==========
LabID
==========
1
Messages
==========
Message
==========
Hello world
Hello world 2
我想加入两个 table,所以输出变成:
=== Lab ID === Messages ===
1 Hello World
如果我这样做
select * from Labs l inner join Messages m on l.LabID = m.LabID
它打印出第一个 ID 两次,因为其中有两条消息 table。我只想select第一条消息。 我尝试添加 top 1 但这没有做任何事情。我真的是 SQL.
的新手您似乎想要每个实验室的最新消息。一种选择是使用横向连接。假设 table messages
有一个名为 labid
的外键列引用 labs
,还有一个名为 id
的列可用于对行进行排序,你会这样表述:
select l.*, m.mesage
from labs l
cross apply (
select top (1) * from messages m where m.labid = l.labid order by m.id desc
) m
如果您想允许没有消息的实验室,请改用 outer apply
。
另一种选择是row_number()
:
select l.*, m.mesage
from labs l
inner join (
select m.*, row_number() over(partition by labid order by id desc) rn
from messages m
) m on m.labid = l.labid and m.rn = 1