我如何从 SQL 服务器中的 parentid 获取所有产品?
how i can get all products from parentid in SQL Server?
我有一个类别 table 命名为 TBL_category 并且包括以下字段:
nid i 身份字段
nid parentid name
1 0 mobile
2 0 tablet
3 1 apple
4 3 iphone
5 2 apple
6 5 ipad
并且我有一个生产 Table TBL_Productions 并且外键是 nid 并且包括以下字段:
productid为身份
productid nid name
1 4 iphone x
2 4 iphone xs
3 4 iphone 11
4 4 iphone 11 pro
5 6 ipad air 2
6 6 ipad mini
7 6 ipad new
8 6 ipad pro
我的问题是:
当用户选择移动类别时,如何显示所有产品?
我与子类别无关,我希望在选择移动或 tablet 类别时显示所有产品。
谢谢
一个选项使用递归查询来恢复“移动”类别及其所有后代,然后将产品 table 与 join
:
with cte as (
select nid from tbl_category where name = 'mobile'
union all
select ca.nid from cte ct inner join tbl_category ca on ca.parentid = ct.nid
)
select p.*
from tbl_productions p
inner join cte ct on ct.nid = p.nid
SELECT * FROM TBL_Productions WHERE nid = category-id-here ;
此查询将 return 为您提供具有特定类别 (nid) 的所有产品。
我有一个类别 table 命名为 TBL_category 并且包括以下字段:
nid i 身份字段
nid parentid name
1 0 mobile
2 0 tablet
3 1 apple
4 3 iphone
5 2 apple
6 5 ipad
并且我有一个生产 Table TBL_Productions 并且外键是 nid 并且包括以下字段:
productid为身份
productid nid name
1 4 iphone x
2 4 iphone xs
3 4 iphone 11
4 4 iphone 11 pro
5 6 ipad air 2
6 6 ipad mini
7 6 ipad new
8 6 ipad pro
我的问题是:
当用户选择移动类别时,如何显示所有产品?
我与子类别无关,我希望在选择移动或 tablet 类别时显示所有产品。
谢谢
一个选项使用递归查询来恢复“移动”类别及其所有后代,然后将产品 table 与 join
:
with cte as (
select nid from tbl_category where name = 'mobile'
union all
select ca.nid from cte ct inner join tbl_category ca on ca.parentid = ct.nid
)
select p.*
from tbl_productions p
inner join cte ct on ct.nid = p.nid
SELECT * FROM TBL_Productions WHERE nid = category-id-here ;
此查询将 return 为您提供具有特定类别 (nid) 的所有产品。