Jump to content

Query: 2 Tables, One Result... checking fields in each table against the other


Rottingham

Recommended Posts

Ok... I'm no GURU at SQl but I run a web server and write custom software. I'm at a stage where I want to limit the query results based on two tables, with one execute();

 

I have two tables,

people

{

  ID (AUTO_INCREMENT)

  First

  Last

  HeadofHouse

  etc...

}

 

family

{

  ID (AUTO_INCREMENT)

  HeadofHouse (THIS WILL EQUAL ID FROM 'people' TABLE)

  etc...

}

 

I want to do this in essence

 

sql->execute("SELECT Last, First, ID FROM people WHERE HeadofHouse='1' AND (people.ID != family.HeadofHouse) ORDER BY Last, First ASC");

 

This query is intended to pull all of the people flagged as the HeadofHouse, but not those who have already been added into the Family table.

 

Any help here? Thanks!

 

Link to comment
Share on other sites

Try this:

 

SELECT Last, First, ID FROM people LEFT JOIN family ON (people.ID = family.HeadofHouse) WHERE people.HeadofHouse = 1 AND family.HeadofHouse IS NULL

 

A left join will put nulls in the right-hand table (family) when there is no matching row in that table.  So by checking for null, you can find those rows present in people but not in family.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.