Re: Hierarchic tables in Queries ??

From: David Portas (REMOVE_BEFORE_REPLYING_dportas_at_acm.org)
Date: 07/13/04


Date: Tue, 13 Jul 2004 10:20:45 +0100

Typically a hierarchy contains all the items in the tree with a nullable,
self-referencing foreign key. Something like this:

CREATE TABLE SomeTable (parent INTEGER NULL REFERENCES SomeTable (id), id
INTEGER NOT NULL PRIMARY KEY, name_e VARCHAR(10) NOT NULL, name_f
VARCHAR(10) NOT NULL)

INSERT INTO SomeTable (parent, id, name_e, name_f)
 SELECT 1024, 1, 'Groceries', '...' UNION ALL
 SELECT 1024, 2, 'Tools', '...' UNION ALL
 SELECT 1, 3, 'Meat', '...' UNION ALL
 SELECT 1024, 4, 'Car', '...' UNION ALL
 SELECT NULL, 1024, 'Foo', '...' -- Missing from your table

Unless you add the missing 1024 value you can't use a foreign key to
guarantee the referential integrity of your hierarchy.

> Most important, I'm looking for a query that would return me
> all the first level THEME (ie: meaning they have 1024 as PARENT) but only
those
> that have an item below at any level.

Try this:

SELECT parent, id, name_e, name_f
 FROM SomeTable AS S
 WHERE parent = 1024
  AND EXISTS
   (SELECT *
    FROM SomeTable
    WHERE parent = S.id)

-- 
David Portas
SQL Server MVP
--


Relevant Pages

  • Re: Data Normalization
    ... CustomerID foreign key. ... of the database whether an SSN would be a good candidate for a primary key. ... applicable that relates that given record to it's parent. ... Create the relationship between the child table and my new parent ...
    (microsoft.public.access.queries)
  • Re: Foreign key question
    ... then the children have two foreign key fields relating ... But each parent will also have only one first child, ... Eg you have a table of planes and a table of propeller types. ...
    (microsoft.public.fox.programmer.exchange)
  • Re: Cascading updates and NULL
    ... foreign key references between the parent and the child and use cascading ... a parent and a child. ... >> DataCol into the child table, cascading updates work fine. ...
    (microsoft.public.sqlserver.programming)
  • Re: Data Normalization
    ... CustomerID foreign key. ... of the database whether an SSN would be a good candidate for a primary key. ... applicable that relates that given record to it's parent. ... Create the relationship between the child table and my new parent ...
    (microsoft.public.access.queries)
  • Re: Cascade Update using only queries
    ... The main form gets the parent table record, ... "Jeff Boyce" wrote: ... It sounds like your "child" tables already have a foreign key to point ... accomplish this by query. ...
    (microsoft.public.access.queries)