我想获取父类别名称。
SELECT u.id,u.fullname,u.email,u.ServiceDescription,
u.Skills,c.Name,r.Reviews,r.RatingValue,ru.Id,
ru.Fullname FROM UserDetails u
INNER JOIN VendorInCategory v ON v.VendorId=u.Id
INNER JOIN CategoryMaster c ON v.CategoryId=c.Id
left join Review r
on r.VendorId = u.id
left JOIN UserDetails ru ON r.CustomerId = ru.id
WHERE ((u.ServiceDescription LIKE '%Plaster%') OR (u.Skills LIKE '%Plaster%') OR
(c.Name LIKE '%Plaster%'))
ORDER BY ISNULL(r.RatingValue, 0) DESC;
现在您可以从下面看到链接我的数据库设计:
calculate average rating in sql server
在这里你可以看到石膏是建筑的子类别(Id:40)
所以如果在categorymaster中找到我正在搜索的任何单词,我想获取parentcategory。
如果在子类别中找到单词,则获取其父类别名称,否则仅获取父类别名称。
任何人都可以编辑我的查询来实现这个功能???
的UserDetails:
id姓名服务描述技巧 1约翰石膏膏
2 abc施工建设
3 xyz石膏膏
4 pqr null null(非供应商)
5 lmn null null(非供应商)
评分
id CustomerId Vendorid评级评论
1 4 1 3 fdd
2 5 1 3 dfg
现在,如果我正在搜索" Plaster"
然后输出应该是:
VendorId ServiceDescription技能评级customername评论ParentCategory
1石膏抹灰3 pqr fdd建筑
3石膏膏3 lmn dfg施工
这里施工(Id 40)是石膏的父类别(Id 44),你可以在图像中看到。如果石膏没有parentid那么ParentCategory名称应该只是石膏。
答案 0 :(得分:0)
试试这个..
SELECT u.id,u.fullname,u.email,u.ServiceDescription,
u.Skills,c.Name,r.Reviews,r.RatingValue,ru.Id,
ru.Fullname,ISNULL(c1.Name,c.Name) AS CategoryName FROM UserDetails u
INNER JOIN VendorInCategory v ON v.VendorId=u.Id
INNER JOIN CategoryMaster c ON v.CategoryId=c.Id
LEFT JOIN CategoryMaster c1 ON c1.Id=c.ParentID
left join Review r
on r.VendorId = u.id
left JOIN UserDetails ru ON r.CustomerId = ru.id
WHERE ((u.ServiceDescription LIKE '%Plaster%') OR (u.Skills LIKE '%Plaster%') OR
(c.Name LIKE '%Plaster%'))
ORDER BY ISNULL(r.RatingValue, 0) DESC;
以下查询将为父级提供:
SELECT c.Name AS Name,c1.Name As Parent FROM CategoryMaster c
LEFT JOIN CategoryMaster c1 on c1.ParentID=c.ID
答案 1 :(得分:-1)
使用公用表表达式(CTE)
示例用户表格结构
userId userName managerId
----------- ---------------- -----------
1 John NULL
2 Charles 1
3 Nicolas 2
4 Neil 5
5 Lynn 1
6 Vince 5
7 Claire 6
为了获得所有顶级经理的姓名,我们需要使用CTE递归调用。
WITH UserCTE AS (
SELECT userId, userName, managerId,0 AS steps
FROM dbo.Users
WHERE userId = 7
UNION ALL
SELECT mgr.userId, mgr.userName, mgr.managerId, usr.steps +1 AS steps
FROM UserCTE AS usr
INNER JOIN dbo.Users AS mgr
ON usr.managerId = mgr.userId
)
SELECT * FROM UserCTE AS u;
上面的查询将返回userid = 7的所有管理器名称。下面是输出
userId userName managerId steps
----------- ---------------- ----------- -----------
7 Claire 6 0
6 Vince 5 1
5 Lynn 1 2
1 John NULL 3