December 15th, 2007 at 5:26 pm

Count over two SQL tables

A bit of SQL that saved my butt lately: Have you ever needed to relate a value from one table to the count of another value in another table? Given you have two tables, one for a timetable, the other for tickets, and you want to find out how many tickets are sold for each tour in the timetable, the following will give it to you (tours.tour_id is related to tickets.ticket_tour_id, who'd have thought of that):

MySQL:
  1. SELECT DISTINCT tour_id, COUNT(ticket_tour_id)
  2. FROM tours
  3. RIGHT JOIN tickets
  4. ON tour_id = ticket_tour_id
  5. GROUP BY ticket_tour_id
  6. ORDER BY departure;

Leave a Comment