sql - 在一对多关系表中选择多条记录的单行
问题描述
在 MSSQL 中,我有两个具有一对多关系的表。
表:
tb_Products:
ID
ProductName
tb_Images:
ProductID
MidPath
在存储过程中,显示产品及其图像(也显示空记录),如果 tb_Images 中有多个 productID,则显示单个记录。
我可以通过这个查询来完成这项工作:
declare @rowIndexToFetch int
set @rowIndexToFetch=0
select p.ID,p.ProductName,p.CategoryID,c.ParentId,
pi.MidPath
from tb_Products p
join tb_Categories c
on p.CategoryID=c.ID
left outer join tb_Images pi
on pi.ProductID=p.ID
where c.ID=3 or c.ParentId=3
order by pi.ID desc
offset @rowIndexToFetch rows
fetch next 1 rows only
但是,如果我使用 offset 和 fetch,我不再可以从 tb_Images 检索 NULL 记录。左外连接不再起作用。
示例记录返回没有偏移提取:
ID ProductName CategoryID ParentId MidPath
154 Chef Ceket 33 3 /cdn/www.sample.com/x
154 Chef Ceket 33 3 /cdn/www.sample.com/y
154 Chef Ceket 33 3 /cdn/www.sample.com/z
1 Eldiven 3 3 NULL
使用偏移量获取:
ID ProductName CategoryID ParentId MidPath
154 Chef Ceket 33 3 /cdn/www.sample.com/x
预计返回:
ID ProductName CategoryID ParentId MidPath
154 Chef Ceket 33 3 /cdn/www.sample.com/x
1 Eldiven 3 3 NULL
问题是,当我使用 offset-fetch 语句时,我无法检索空记录。我怎样才能解决这个问题?
解决方案
select distinct p.ID,p.ProductName,p.CategoryID,c.ParentId,
pi.MidPath
from tb_Products p
join tb_Categories c
on p.CategoryID=c.ID
left outer join tb_Images pi
on pi.ProductID=p.ID
where c.ID=3 or c.ParentId=3
where c.ID=3 or c.ParentId=3
推荐阅读
- javascript - 如何在 MongoDB 中过滤子文档?
- sql-server - 从不同的服务器查询地理数据类型
- c# - 我在 c#/UWP 中需要我的域控制器的唯一标识符
- c++ - 尝试使用 clang++ v12 将两个 C++20 模块一起构建为一个模块
- docker - docker - 悬空(无)中间图像
- c# - 当用户没有在文本框中输入任何内容时,如何让代码使用不同的变量?
- graphql - 您如何定义 upsert(如果存在更新则插入)甚至使用 graphql 的更新?
- python - Apache Beam python fileio.WriteToFiles oversharding
- javascript - $.ajax() 不是一个函数,即使安装了普通的 jQuery
- uart - 初始化 Uart 引脚作为 PWM 输出