使用Count函数SQL依靠数据库

时间:2015-04-27 12:22:50

标签: sql count

我有像这样的数据库架构

Flights(flno,from,to,distance,departs,arrives,price)
Aircraft(aid,aname,cruisingRange)
Certified(employee,aircraft)
Employees(eid,ename,salary)

其中Flno是主键,每条路线对应一个" flno"。

所以我有这个问题要回答Schema

对于每位飞行员,列出其员工ID,姓名和路线数量 他可以试点。

我有这个SQL,这是正确的吗? (我可以测试,因为我没有数据库的数据)。

 select eid, ename, count(flno) 
 from employees, flights 
 groupby flno

1 个答案:

答案 0 :(得分:4)

这是一个简单的问题,但是每个人都提到你在员工和航班之间没有任何联系。关系停在certified

你显然已经或将会建立一些关系。我写了一个查询,考虑到你将在员工和航班之间建立多对多的关系,这将给你计数。这意味着员工可以拥有多个航班,许多员工可以进行单次航班。

航班(flno,从,到,距离,离开,到达时,价格) 飞机(援助,aname,cruisingRange) 认证(员工,飞机) 雇员(EID,ENAME,薪水)

select
  e.eid employee_id,
  e.ename employee_name,
  count(*)
from
  employees e 

  inner join certified c on
    c.employee = e.eid

  inner join aircraft a on
    a.aid = c.aircraft

  inner join aircraft_flights af on -- new table that you would need to create
    af.aircraft = a.aid and

  inner join flights f on
    f.flno = af.flno -- not I made up a relationship here which needs to exist in some for or another
group by
  e.eid,
  e.ename

我希望这至少能告诉你如何正确地编写一个count语句,但是你应该了解joins

希望有所帮助。

修改

如果没有关系并在评论中工作,您可以获得如下计数。

select
  e.eid employee_id,
  e.ename employee_name,
  count(*)
from
  employees e 

  inner join certified c on
    c.employee = e.eid

  inner join aircraft a on
    a.aid = c.aircraft

  inner join flights f on
    f.distance <= a.cruisingRange
group by
  e.eid,
  e.ename