Selecting from a self referencing table?

Discussion in 'Databases' started by gandalf117, Mar 18, 2011.

  1. #1
    I have a table in which the ids of some rows are present under another column as foreign keys. So for example if employee with id 09 served no customers, employee with id 10 served one customer and employee with id 11 served 3 customers you will have a table like this one:

    Id col2 col3
    09 EmployeeName 2
    10 EmployeeName 2
    11 EmployeeName 3
    13 CustomerName 11
    14 CustomerName 11
    15 CustomerName 10
    16 CustomerName 11

    Is there a way to select with a single query only the employees who haven't served any customers? In this case there is only one employee who fits this condition. My guess is that the query should select only the employees whose id isn't present in col3 but how do you do this with one query?

    Is this possible at all to do with a single query?
    How would you do it?
     
    gandalf117, Mar 18, 2011 IP
  2. Aquarezz

    Aquarezz Notable Member

    Messages:
    3,009
    Likes Received:
    69
    Best Answers:
    0
    Trophy Points:
    225
    #2
    Aquarezz, Mar 18, 2011 IP
  3. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #3
    I think I can help, but your table structure is a little sketchy and throwing me off. Specifically the values in col2--Why are their EmployeeName and CustomerName, shouldn't it all be customer names? Does the first record in your example mean employee 2 served an employee? Also, could you provide specific table and field names including the names for the table that holds all your employees?
     
    Last edited: Mar 18, 2011
    plog, Mar 18, 2011 IP
  4. AstarothSolutions

    AstarothSolutions Peon

    Messages:
    2,680
    Likes Received:
    77
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You havent explained what column 3 holds when the entity is an employee (when its a customer column 3 is the employee's ID)
     
    AstarothSolutions, Mar 19, 2011 IP
  5. ACME Squares

    ACME Squares Peon

    Messages:
    98
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    This query would be a lot easier if your data was better normalized.
    Then your could GROUP BY your transactions by employee_id and find which ones are zero.
     
    ACME Squares, Mar 19, 2011 IP