我正在尝试将MySQL数据库转换为MSSQL数据库,但我在翻译查询时正在尝试一些问题,特别是以下内容:
的MySQL
SELECT GROUP_CONCAT( parent.Name
ORDER BY parent.Lft
SEPARATOR "«" ) AS Path, node.Description
FROM `DB`.`Categories` AS node, `DB`.`Categories` AS parent
WHERE node.Lft BETWEEN parent.Lft AND parent.Rgt AND node.ID = 2
GROUP BY node.Name, node.ID
ORDER BY node.Lft LIMIT 1;
我得到的结果就是这个,这是我想要获得的结果:
+-------------------------------+
| Path |
+-------------------------------+
| Master Node « Vehicles « Cars |
+-------------------------------+
MS SQL
我尝试使用帖子https://stackoverflow.com/a/5981860/2098159
中的建议重新创建MySQL查询SELECT STUFF((SELECT ' « ' + [Name] FROM [DB].[dbo].[Categories] FOR XML PATH ('')), 1, 1, '') AS [Path]
FROM [DB].[dbo].[Categories] AS node, [DB].[dbo].[Categories] AS parent
WHERE node.[Lft] BETWEEN parent.[Lft] AND parent.[Rgt] AND node.[ID] = 7
GROUP BY node.[Name], node.[ID], node.[Lft] ORDER BY node.[Lft];
我得到的结果就是这个,无论我选择哪个ID:
+---------------------------------------------+
| Path |
+---------------------------------------------+
| « Master Node « Vehicles « Cars « Computers |
+---------------------------------------------+
此时我只创建一个包含4条记录的表:主节点,车辆,汽车和计算机;只是为了测试。
我不知道我错过了什么。有没有人有建议?
提前致谢。
答案 0 :(得分:1)
问题是您缺少xml路径部分中的条件:
SELECT
STUFF((
SELECT ' « ' + [Name]
FROM [DB].[dbo].[Categories] C
WHERE C.ID = node.ID -- a criteria here is needed to get correct rows
FOR XML PATH ('')), 1, 1, '') AS [Path]
FROM
[DB].[dbo].[Categories] AS node,
[DB].[dbo].[Categories] AS parent
WHERE
node.[Lft] BETWEEN parent.[Lft] AND parent.[Rgt] AND
node.[ID] = 7
GROUP BY
node.[Name],
node.[ID],
node.[Lft]
ORDER BY
node.[Lft];
我的假设是ID足以识别正确的行。
答案 1 :(得分:0)
这里我放置了正确的查询。
SELECT STUFF((SELECT CAST(' « ' AS varchar(MAX)) + parent.name
FROM Categories AS node, Categories AS parent
WHERE node.[Lft] BETWEEN parent.[Lft] AND parent.[Rgt]
AND node.[ID] = 7
ORDER BY node.lft
FOR XML PATH('')), 1, 1, '') as Path
我唯一无法删除的是第一个'«'
+---------------------------------+
| Path |
+---------------------------------+
| « Master Node « Vehicles « Cars |
+---------------------------------+