简体   繁体   中英

MySQL query Count in subquery

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 ;-)

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM