0

OK、これはややこしくなってきているので、新しい質問を書くことにしました。

カテゴリ テーブルの行が子カテゴリかどうかを確認する必要があります。次に、子がどの親カテゴリに属しているかを確認する必要がありますか?

親カテゴリには、0 のカテゴリ ID と ParentCategoryID があります。子カテゴリには、カテゴリ ID と ParentCategoryID (例: 30) があります。

カテゴリ テーブル:

ID PCID NAME
10  0   Computers
11  10  Software
12  10  Hardware

これは私が試したことです:

これにより、親カテゴリが表示されます (PCID 0 が親であるため)。

SELECT        CategoryID, ParentCategoryID, Name, Published, Deleted, PictureID
FROM          Nop_Category
WHERE        (Deleted = 0) 
AND          (Published = 1) 
AND          (ParentCategoryID = 0)
4

1 に答える 1

4

テーブルに自己結合して、子の実際の親を見つけます。

SELECT        c1.CategoryID, c2.ParentCategoryID, c1.Name, c2.Name as ParentName, c1.Published, c1.Deleted, c1.PictureID
FROM          Nop_Category c1
JOIN          Nop_Category c2 on c1.ParentCategoryId = c2.CategoryId
WHERE        (c1.Deleted = 0)  
AND          (c1.Published = 1)  
AND          (c1.ParentCategoryID = 10)

これにより、カテゴリ「コンピュータ」の両方の子が返されます。それはあなたが探しているものですか?

もちろん、これを逆にして、特定の親のすべての子またはすべての親からのすべての子を表示できます。

SELECT c.*, p.* -- shortened, but you should pick specific columns

FROM Nop_Category p -- parent
JOIN Nop_Category c ON c.ParentCategoryId = p.CategoryId -- children

WHERE p.ParentCategoryId = 0 -- all top level parents


SELECT c.*, p.* -- shortened, but you should pick specific columns

FROM Nop_Category p -- parent
JOIN Nop_Category c ON c.ParentCategoryId = p.CategoryId -- children

WHERE p.CategoryId = 10 -- only the "Computers" category

または、カテゴリ「コンピューター」の子だけが必要な場合は、ParentCategoryId を 10 に変更します。

SELECT        CategoryID, ParentCategoryID, Name, Published, Deleted, PictureID  
FROM          Nop_Category  
WHERE        (Deleted = 0)   
AND          (Published = 1)   
AND          (ParentCategoryID = 10)
于 2012-07-08T17:09:05.850 に答える