对于模糊的标题感到抱歉,不确定如何描述它
基本上我有一张这样的桌子(汽车由^^隔开)
id| cars
-------------------------
1|car1 ^^ car2 ^^ car3
2|car2 ^^ car3
3|car1
4|car1 ^^ car 2
5|car3
基本上我想列出所有与他们匹配的id的汽车
car |id
-------------
car1|1,3,4
car2|1,2,4
car3|1,2,5
在mySQL中可以做到这一点吗?它的查询是什么?
非常感谢任何帮助!
答案 0 :(得分:0)
这应该有效。我正在使用表变量“@Cars”来填充我的结果,但是,您可以将其替换为数据库中的实际表名。
--Table Defination:
DECLARE @Cars TABLE
(ID INT IDENTITY,
Cars VARCHAR(255)
);
INSERT INTO @Cars(Cars)
VALUES('car1 ^^ car2 ^^ car3');
INSERT INTO @Cars(Cars)
VALUES('car2 ^^ car3');
INSERT INTO @Cars(Cars)
VALUES('car1');
INSERT INTO @Cars(Cars)
VALUES('car1 ^^ car2');
INSERT INTO @Cars(Cars)
VALUES('car3');
--SQL
SELECT distinct Cars, STUFF(
(
SELECT ', '+CAST([id] AS NVARCHAR(256))
FROM
(
SELECT A.id,
LTRIM(RTRIM(Split.a.value('.', 'VARCHAR(100)'))) AS Cars
FROM
(
SELECT ID,
CAST('<M>'+REPLACE(Cars, '^^', '</M><M>')+'</M>' AS XML) AS String
FROM @Cars
) AS A
CROSS APPLY String.nodes('/M') AS Split(a)
) T1
WHERE T1.Cars = T2.Cars
FOR XML PATH('')
), 1, 1, '') AS id
FROM
(
SELECT A.id,
LTRIM(RTRIM(Split.a.value('.', 'VARCHAR(100)'))) AS Cars
FROM
(
SELECT ID,
CAST('<M>'+REPLACE(Cars, '^^', '</M><M>')+'</M>' AS XML) AS String
FROM @Cars
) AS A
CROSS APPLY String.nodes('/M') AS Split(a)
) T2;