【问题标题】:SQL Join and concatenate rowsSQL 连接和连接行
【发布时间】:2012-10-17 18:24:59
【问题描述】:

我有两个表之间的多对多关系。

God_Restaurants 包含我的餐厅。

God_RestaurantKat 包含不同的类别。

God_RestKatReference 包含两列,每列包含两个表的ID。

以下语句是我能想到的,但没有给我想要的输出。

DECLARE @Names VARCHAR(8000) 
SELECT DISTINCT R.RestaurantID as Restaurantid, 
                R.RestaurantName as Restaurantname, 
                K.RestaurantKatName as RestKatName 
FROM God_Restaurants R 
LEFT JOIN God_RestKatReference as GodR ON R.RestaurantId = Godr.RestaurantId 
LEFT JOIN God_RestaurantKat as K ON GodR.RestaurantKatId = K.RestaurantKatId 
WHERE R.RestaurantPostal = 7800

我希望输出是关于餐厅的信息,并且在最后一列中是一个串联的类别行。

【问题讨论】:

标签: sql sql-server


【解决方案1】:

要连接值,您可以使用for xml path('')。 xml路径错误的解决方法,特殊字符请使用valuetype

declare @Temp table (id int, Name nvarchar(max))
declare @date datetime
declare @i int

insert into @Temp
select 1, 'asasd' union all
select 1, 'sdsdf' union all
select 2, 'asdad' union all
select 3, 'asd<a?>&sdasasd' union all
select 3, 'fdgdfg'

select @i = 1
while @i < 9
begin
    insert into @Temp
    select id, Name from @Temp

    select @i = @i + 1
end

select count(*) from @Temp

select @date = getdate()

select
    A.id,
    stuff((select ', ' + TT.Name from @Temp as TT where TT.id = A.id for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '') as Names
from @Temp as A
group by A.id

select datediff(ms, @date, getdate())

select @date = getdate()

select distinct
    A.id,
    stuff((select ', ' + TT.Name from @Temp as TT where TT.id = A.id for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '') as Names
from @Temp as A

select datediff(ms, @date, getdate())

你也可以使用变量解

declare @temp nvarchar(max)

select @temp = isnull(@temp + ', ', '') + str
from (select '1' as str union select '2' as str union select '3' as str) as A

select @temp

【讨论】:

  • 第一个查询的更好解决方案是使用group by id 而不是distinct。对于distinct,子查询将执行5 次,对于group by,它将使用此样本数据执行3 次。对于更大的数据集,您会发现性能有所不同。
  • 是的,但它还需要某种min 来连接字段。我认为最好的解决方案是在子查询中获取distinct ids,然后获取连接数据
  • 不,它不需要min。 distinct 版本不仅会在 id 上做不同的事情,它还会在 id 和连接字符串的组合上做不同的事情。
  • 是的,你是对的,在这样的查询中使用distinct 是不好的,并且你不需要对连接字段进行聚合。我已经更改了一个查询,添加了查询的毫秒数。对于 1280 行和 3 个 id,group by 执行 3 毫秒,distinct 执行大约 3000 毫秒。因此,如果您有少量 id 和大量行,您可以真正注意到性能上的差异。谢谢
猜你喜欢
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 2011-03-16
  • 2013-07-21
  • 1970-01-01
  • 2013-11-04
相关资源
最近更新 更多