dqzow3859 2013-04-24 17:57
浏览 36
已采纳

带有连接和计数的mySQL查询

I have a my sql DB and using php to access it.

My tables look like:

Flights Table Flight ID, Time, Airport

Seats Table Flight ID, Seat Number

I have the following query:

SELECT f.FlightID 'ID', Count(*) 'Seats Booked' FROM flights f, seats s  GROUP BY f.FlightID

I want the out put to be

Flight ID Seats Booked

ID Num seats book

The problem is currently it shows this:

[{"ID":"0","Seats Booked":"37"},{"ID":"1234","Seats Booked":"37"}] (The output is JSON encoded)

When it should be be like 10 and 27 if you follow me? It doesnt seem to be the join correctly.

Please give an explanation of what im doing wrong rather than just an answer.

Thanks!

  • 写回答

4条回答 默认 最新

  • doufeiqiong3515 2013-04-24 18:07
    关注

    LmC,

    You did not use the clause to make the join. Thats why you got a sum for each grouped instruction.

    The correct instruction using your syntax should be something like:

    SELECT f.FlightID 'ID', Count(*) 'Seats Booked' 
    FROM flights f, seats s  
    where s.FlightId = f.FlightId
    GROUP BY f.FlightID
    

    Using inner join syntax should be something like:

    SELECT f.FlightID 'ID', Count(*) 'Seats Booked' 
    FROM flights f
    inner join seats s  
    on  s.FlightId = f.FlightId
    GROUP BY f.FlightID
    

    You can do the something without using the flight table. The flight table is not making any difference because you are returning a group of flightid. And the table seats has flightid. The statement below should be enough. This is true if you are not concerned about flights without booked seats

    SELECT s.FlightID 'ID', Count(*) 'Seats Booked' 
    FROM seats s  
    GROUP BY s.FlightID
    

    If you wanna show flights without booked seats, then you should use left join to flights. The statement below will solve this issue.

    SELECT f.FlightID 'ID', Count(*) 'Seats Booked' 
    FROM flights f
    left join seats s  
    on  s.FlightId = f.FlightId
    GROUP BY f.FlightID
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像