Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select all from one table of joint tables

I am a SQL beginner and I need to figure out this query: I have three tables joined together from which I am counting certain value, like this:

SELECT SEATS_MAX-COUNT(BOOKING_ID) 
FROM FLIGHTS 
  INNER JOIN PLANES ON FLIGHTS.PLANE_ID=PLANES.PLANE_ID 
  LEFT JOIN BOOKINGS ON FLIGHTS.FLIGHT_ID=BOOKINGS.FLIGHT_ID 
GROUP BY SEATS_MAX;

This returns number of free seats in a flight. But I would like to get all the columns from FLIGHTS (as in SELECT * FROM FLIGHTS;) plus the count number. i.e. something like

SELECT FLIGHTS.*, SEATS_MAX-COUNT(BOOKING_ID) 
FROM FLIGHTS 
  INNER JOIN PLANES ON FLIGHTS.PLANE_ID=PLANES.PLANE_ID 
  LEFT JOIN BOOKINGS ON FLIGHTS.FLIGHT_ID=BOOKINGS.FLIGHT_ID 
GROUP BY SEATS_MAX;

but this doesn't work (invalid user.table.column, table.column or column specification). Is there a way to achieve this? I'm using Oracle db.

Thanks

like image 340
Martin Melka Avatar asked Sep 19 '25 04:09

Martin Melka


1 Answers

In the group by you need to have all the column not aggregated.

So you query has to become:

      SELECT FLIGHTS.*, 
             SEATS_MAX-COUNT(BOOKING_ID) 
        FROM FLIGHTS 
  INNER JOIN PLANES 
          ON FLIGHTS.PLANE_ID = PLANES.PLANE_ID 
   LEFT JOIN BOOKINGS 
          ON FLIGHTS.FLIGHT_ID = BOOKINGS.FLIGHT_ID 
    GROUP BY FLIGHTS.Column1,
             ...
             FLIGHTS.ColumN,
             SEATS_MAX;

Edit: To list all columns of you table you can use the following query

  SELECT 'FLIGHTS.' || column_name
    FROM user_tab_columns
   WHERE table_name = 'FLIGHTS'
ORDER BY column_id;

This should make your life a bit easier, then copy and paste

like image 127
mucio Avatar answered Sep 20 '25 18:09

mucio