首页 > 解决方案 > 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

标签: sqlsql-server

解决方案


一个简单的方法使用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;

顺序可能是最新的或最旧的或最大的或最小的或其他。


推荐阅读