views:

153

answers:

2

I am trying to create a query which will return all rows of a table CLASSES that do not matched with another table named CHILD_CLASSES. These two tables look like this,

The table CLASSES is a self referencing table so the top CLASS does not have a parent_id. The Parent ID row is created from the class_id row. So when I inserted A1 as a sub class to A then its parent ID is 1 because A's class_id is 1. And then A11 is a sub class to A1 as well as A12 so their parent_ids will be 2.

CLASS_ID  |  PARENT_ID | CLASS_NAME
-----------------------------------
  1       |     --     |    A
  2       |     1      |    A1
  3       |     2      |    A11
  4       |     2      |    A12

I then have another table CHILD_CLASSES which will store the children of each CLASS. Since A is the top Class it will have the children of everything below it, A1, A11, and A12. A1 will only have A11 and A12. It looks like this

ID   | PARENT_ID | CLASS_ID
----------------------------
  1  |     1     |    2
  2  |     1     |    3
  3  |     1     |    4
  5  |     2     |    3
  6  |     2     |    4

This is a little archaic but all I am really looking for is a query that will return to me the rows in the CLASSES table that do not have children for a given CLASS_ID. For example, if I run the query on A1 which is class_id 2, it will return to me rows with the class_ids of 1 because the CLASS A is CLASS that has not been set as a child of A1 in the CHILD_CLASSES table. If I were to run the query on A11 then I would get class_ids 1, 2, and 4 because A1 has no children yet, and so on. Any help would be much appreciated.

A: 
SELECT  *
FROM    classes c
WHERE   class_id NOT IN
        (
        SELECT  class_id
        FROM    child_classes cc
        WHERE   cc.parent_id = 2
        )
        AND class_id <> 2
Quassnoi
@Fred: `classes` corrected. As for the `SELECT` clause, the question reads "the rows in the `CLASSES` table that do not have children for a given `CLASS_ID`".
Quassnoi
@Quassnoi: ok ok but mysql_quest said: " If I were to run the query on A11 then I would get class_ids 1, 2, and 4 because A1 has no children yet, and so on. Any help would be much appreciated. "
Fred
@Quassnoi: Your second select doesn't seem to work, it returns only 2 instead of 3 and 4
Fred
A: 

Correction of Quassnoi request:

SELECT  class_id 
FROM    CLASSES c 
WHERE   c.class_id NOT IN 
        ( 
        SELECT  cc.class_id
        FROM    CHILD_CLASSES cc 
        WHERE   cc.parent_id = 2 
        ) 
        AND c.class_id <> 2 
Fred
Indeed, MySQL will handle case differently on different platforms: on Windows, table names are case insensitive, while they are case sensitive on platforms like Linux.
Frank Shearar
I know it but corrections were not on table names. Quassnoi has made corrections on his post.
Fred