SQL小提琴
MS SQL Server 2008 架构设置:
create table Product
(
ID int,
Name varchar(10)
)
create table Category
(
ID int,
Name varchar(10)
)
create table Tags
(
ID int,
Name varchar(10)
)
create table ProductCategory
(
productId int,
categoryId int
)
create table CategoryTags
(
categoryId int,
tagId int
)
insert into Product values(1, 'Product 1')
insert into Category values(1, 'Animals')
insert into Category values(2, 'Countries')
insert into Category values(3, 'Color')
insert into Tags values(1, 'Bird')
insert into Tags values(2, 'Duck')
insert into Tags values(3, 'Dog')
insert into Tags values(4, 'Candada')
insert into Tags values(5, 'Russia')
insert into Tags values(6, 'Japan')
insert into Tags values(7, 'Black')
insert into Tags values(8, 'Red')
insert into Tags values(9, 'White')
insert into ProductCategory values(1, 1)
insert into ProductCategory values(1, 2)
insert into ProductCategory values(1, 3)
insert into CategoryTags values(1, 1)
insert into CategoryTags values(1, 2)
insert into CategoryTags values(1, 3)
insert into CategoryTags values(2, 4)
insert into CategoryTags values(2, 5)
insert into CategoryTags values(2, 6)
insert into CategoryTags values(3, 7)
insert into CategoryTags values(3, 8)
insert into CategoryTags values(3, 9)
查询 1:
select P.ID,
P.Name,
(
select ';'+C.Name+':'+
(
select ','+T.Name
from CategoryTags as CT
inner join Tags as T
on CT.tagId = T.ID
where CT.categoryId = C.ID
for xml path(''), type
).value('substring(text()[1], 2)', 'varchar(max)')
from ProductCategory as PC
inner join Category as C
on PC.categoryId = C.ID
where PC.productId = P.ID
for xml path(''), type
).value('substring(text()[1], 2)', 'varchar(max)') as ColumnName
from Product as P
结果:
| ID | NAME | COLUMNNAME |
-----------------------------------------------------------------------------------------------
| 1 | Product 1 | Animals:Bird,Duck,Dog;Countries:Candada,Russia,Japan;Color:Black,Red,White |