Home > OS >  MySQL query Count in subquery
MySQL query Count in subquery

Time:11-13

Good day,

I have a question.

I have a table called event_booking. Here we have events and each event has a separate location.

So we have event

event_booking has :

  1. booking_id
  2. booking_name
  3. booking_date
  4. booking_location
  5. booking_comments

The type of structure is :

  • booking_id = integer
  • booking_name = varchar
  • booking_date = datetime
  • booking_location = integer
  • booking_comments = text

Now I want to create a Query that lists all event locations and for each location which event has been set there.

So :

I would get a result like :

  1. booking_location = 4 & no_bookings = 256
  2. booking_location = 7 & no_bookings = 34
  3. booking_location = 6 & no_bookings = 128
  4. booking_location = 3 & no_bookings = 24

Now I have fiddled a lit and created the following QUERY. That's correct in terms of syntax. But totally wrong in terms of output.

SELECT `booking_location`, `booking_location` AS `selector`, (SELECT COUNT(1) FROM `event_booking` WHERE `booking_location` = `selector`) AS `no_bookings` FROM `event_booking` WHERE `booking_location` IN (SELECT `booking_location` FROM `event_booking` GROUP BY `booking_location`) 

I know I am missing something. But what I am missing.. Thanks in advance ;-)

CodePudding user response:

Assuming that you really just want to count the booking locations (based on your example of a possible result, and also your query code):

  SELECT booking_location,
         COUNT(booking_location) AS no_bookings
    FROM event_booking
GROUP BY booking_location;
  • Related