Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to set your table up for a recursive one-to-many relationship, like this making a few assumptions about data types):</p> <pre><code>CREATE TABLE [Categories] ( CategoryID int NOT NULL PRIMARY KEY, CategoryName varchar(255) NOT NULL, ParentCategoryID int NULL, -- Level field is not needed; can be dynamically determined CONSTRAINT FK_Child_to_Parent FOREIGN KEY (ParentCategoryID) REFERENCES [Categories] (CategoryID) ) </code></pre> <p>In order to query this table in general, you need to use a self-join, like this (note the from/join; this is the part you will re-use):</p> <pre><code>select child.*, parent.* from Categories child join Categories parent on child.ParentCategoryID = parent.CategoryID </code></pre> <p>You can tell when you are looking at a parent category because the value for <code>ParentCategoryID</code> will be <code>NULL</code>. To answer your question of how to get child categories for your page given a parent ID, you can use this:</p> <pre><code>select child.CategoryID, child.CategoryName from Categories child join Categories parent on child.ParentCategoryID = parent.CategoryID where parent.ParentCategoryID = [some value] </code></pre> <p>There are tons of tutorials/designs out there if you Google "recursive database table" or related terms; for starters, here is one (picked at random):<a href="http://www.tomjewett.com/dbdesign/dbdesign.php?page=recursive.php" rel="nofollow">http://www.tomjewett.com/dbdesign/dbdesign.php?page=recursive.php</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload