Jump to content

Query Multiple Tables


SharkBait

Recommended Posts

I have two tables that reference each other but what I am trying to do is select a row in one table and then subtract a COUNT() from another query to give me the result.

 

Let's see if i can explain this better.

 

Table1

 

id | seats | venue

--+------+--------

1  |  30  |  GM Place

--+------+--------

2  |  34  |  BC Place

--+------+--------

 

Table2

 

id | table1_id  |  customer

--+-----------+-------------

1  | 1            |  Jim Bob

--+-----------+-------------

2  | 1            |  Billy Bob   

--+-----------+-------------

3  | 2            | Sammy D 

--+-----------+--------------

 

So I want to be able to return from Table1 the remaining `seats` by counting up the rows and minusing the ones from table2 based on Table1.id = Table2.table1_id

 

So the result row would return 28 seats left for `GM Place` and 33 seats for `BC Place`

 

Link to comment
Share on other sites

Ah ok. I thought I could do a query within a query but wasn't quite sure how to go about doing it.

 

I also made sure I renamed the field because seats - (SELECT COUNT(*) etc is a bit much to put into a variable. lol

 

SELECT *, seats - (SELECT * FROM table2 WHERE table1_id = id) as seats FROM table 1

 

Works nicely thanks!

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.