2012-10-17 2 views
1

두 테이블간에 다 대다 관계가 있습니다.SQL 행 조인 및 연결

테이블 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 

결과물은 식당에 관한 정보이고 마지막 열에는 범주의 연결된 행이 있습니다.

+1

를 사용할 수 있습니다. 그래서, 처음에는 http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/f09d4166-2030-41fe-b86e-392fbc94db53/ –

+0

[Simulating group \ _concat MySQL function in 가능한 중복을보십시오. MS SQL Server 2005?] (http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005) 발견. 그리고 [this answer] (http://stackoverflow.com/a/5981860/44853) –

답변

2

값을 연결하려면 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()) 

또한 어디 선가 SO에 대한 중복 질문이 세 사람이 거기에 확신 해요,하지만 난 지금을 찾을 수없는 변수 솔루션을

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 
+0

첫 번째 쿼리를위한 더 좋은 해결책은'distinct' 대신'group by id'를 사용하는 것입니다. 'distinct'를 사용하면 sub query가 5 번 실행되고'group by '을 사용하면이 샘플 데이터로 3 번 실행됩니다. 더 큰 데이터 세트를 사용하면 성능 차이가 있음을 알 수 있습니다. –

+0

네,하지만 연결된 종류의 필드에는 어떤 종류의'min'이 필요합니다. 가장 좋은 해결책은 하위 쿼리에서'distinct 'ID를 얻은 다음 연결된 데이터를 얻는 것입니다. –

+1

아니요,'min'이 필요하지 않습니다. 별개의 버전은 ID와 ID 및 연결 문자열의 구별을 위해 고유 ID를 수행합니다. –