sql - SQL Server 合并一些列
问题描述
我在 SQL Server 中有这两个表:
产品表
id | name | description
---+-----------+-------------
1 | Product 1 | abd
2 | Product 2 | abd
3 | Product 3 | abd
4 | Product 4 | abd
图像表
id | name | idproduct
---+----------------+-----------
1 | Product1-1.jpg | 1
2 | Product1-2.jpg | 1
3 | Product1-3.jpg | 1
4 | Product2-1.jpg | 2
5 | Product2-2.jpg | 2
6 | Product3-1.jpg | 3
我需要从Product
表中选择仅包含一张图片的产品,当产品没有任何图片时,显示空值,
我使用了这段代码:
select
p.id, p.name, p.description,
isnull(i.name, 'Not available') as image
from
Products p
left outer join
Images i on p.id = i.idproduct
where
p.idcategory = 7
group by
p.name, p.id, i.name, p.description
但输出是
id | name | image | description
---+-----------+-----------------+-------------
1 | product 1 | Product1-1.jpg | abc
1 | product 1 | Product1-2.jpg | abc
1 | product 1 | Product1-3.jpg | abc
2 | product 2 | Product2-1.jpg | abc
2 | product 2 | Product2-2.jpg | abc
3 | product 1 | Product3-1.jpg | abc
4 | product 1 | Not available | abc
如何更改我的查询以选择这些项目:
id | name | image | description
---+-----------+-----------------+-------------
1 | product 1 | Product1-1.jpg | abc
2 | product 2 | Product2-1.jpg | abc
3 | product 1 | Product3-1.jpg | abc
4 | product 1 | Not available | abc
解决方案
一个简单的方法使用apply
. 如果您不关心哪个图像,您可以使用:
select p.*, i.image
from product p outer apply
(select top (1) i.image
from image i
where i.idproduct = p.id
) i;
这会返回一个NULL
图像值,这对我来说比字符串更有意义——更明显的是该值丢失了。
如果您关心返回哪个图像,order by
请在子查询中使用。例如,对于随机图像:
select p.*, i.image
from product p outer apply
(select top (1) i.image
from image i
where i.idproduct = p.id
order by newid()
) i;
顺序可能是最新的或最旧的或最大的或最小的或其他。
推荐阅读
- mysql - 简单 INDEX 查询的可怕性能
- windows - 如何撤消兼容性管理员中的“安装”?
- chromium - ChromiumFx / Cef 如何向渲染器进程发送自定义 IPC 消息并执行自定义 c# 代码
- sql - 返回Oracle中表达式的数据类型
- jquery - MouseFlow 手动触发
- windows - 在 postgres 中,编辑 pg_hba.conf 没有启用无密码登录
- php - 使用 PHP 将数组插入数据库
- python - 如何使用另一个数据框的 MultiIndex 过滤一个数据框的列
- javascript - bind vs apply:这两者有区别吗?
- java - 杰克逊序列化通用但不反序列化