0

These are the database table i have:

trip

  • id
  • capacity
  • ...

tripRegisteration

  • id
  • tripId
  • firstname
  • lastname
  • phone
  • ...
  • registerationState

what i can do

I want a sql query which will give me the trips which has enough free capacity. The tripRegisteration.registerationState for valid registeration is approved.

Of course i can first do this:

SELECT COUNT(*) 
FROM tripRegisteration 
WHERE registerationState = "approved"
GROUP BY tripId

Then i have a table which would tell me each trip registered and then i can do:

SELECT *
FROM trip
WHERE capacity < PhpReplacesThis AND id=PhpReplacesThisToo

But for each trip i have to execute the above code, it consumes so much time and the resources start to run out, and because there are a lot of trips (and a lot of sql queries) it wouldn't be efficient.

What i can't do but it's nice

It would be much more efficient if i could do that in just one sql query, which would give me a table which contains the trips which has enough capacity.

Is it really nice? Well my measurement shows that when the number of sql queries i run with php is so much the application would start crawling and consume a lot of time. I remember if i make sql queries compact (one bigger query instead of a million small query) it would make the whole application much faster. I just have experienced it and measured the time in another project if i am wrong correct me. Of course that's another question and this explanation is written for making the situation clear. My main question is how i can get the result in one sql query?

4

2 回答 2

0

This query uses just a JOIN and no nested-queries

SELECT trip.id,trip.capacity,trip.moreColumns,count(*) as number_of_registrations
FROM trip 
JOIN tripRegisteration
ON trip.id=tripRegisteration.tripId
WHERE registerationState = "approved"
GROUP BY trip.id,trip.capacity,trip.moreColumns
HAVING trip.capacity< number_of_registrations
于 2013-09-13T15:17:29.777 回答
0

您只需要使用连接和子选择,如下所示:

SELECT * FROM trip LEFT JOIN (select count(1) as regCount, 
tripId from tripRegisteration where tripId = trip.id and 
registerationState="approved") as registrations 
ON registrations.tripId = trip.id 
WHERE trip.capacity < registrations.regCount
于 2013-09-13T15:01:26.873 回答