SQL查询,我做错了什么?

时间:2014-04-02 07:40:47

标签: mysql sql

你好,我正在尝试进行此查询,但我遇到了麻烦。任何人都可以帮我一把,我会在下面列出我做过的事情。

  1. 每个验光师的忙碌程度。您的SQL语句应返回所有验光师的全名,以及他们进行的约会总数。您必须使用“Optometrist”一词而不是positionID来选择语句中的验光师。请注意,即使是约会的验光师也应该显示在结果中。

    我做了什么..

    SELECT firstName, lastName, optometristID, COUNT(optometristID)
    FROM employee
    LEFT JOIN appointment ON employee.employeeID=appointment.optometristID
    GROUP BY (optometristID)
    
  2. 所有客户的全名,电子邮件和主要电话号码以及发票总数按姓氏的升序排列。请注意,即使是零发票的客户也应显示在结果中。

    我写的是什么..

    SELECT c.firstName, c.lastName, c.primaryPhone,
    (SELECT count(*) from invoice where customerID = c.customerID) as numInvoices
    FROM customer c, invoice i
    WHERE c.customerID = c.customerID 
    ORDER BY lastname ASC
    
  3. 谢谢!

2 个答案:

答案 0 :(得分:1)

第一个对我来说没问题

第二个应该是

SELECT c.firstName, c.lastName, c.primaryPhone,
(SELECT count(*) from invoice where customerID = c.customerID) as numInvoices
FROM customer c
ORDER BY lastname ASC

OR

SELECT c.firstName, c.lastName, c.primaryPhone,
count(i.customerID ) as numInvoices
FROM customer c left join invoice i
on i.customerID = c.customerID 
group by c.customerID 
ORDER BY lastname ASC

最后一个应该更快

答案 1 :(得分:0)

在第二个查询中,您必须编写

WHERE c.customerID = i.customerID 

而不是

WHERE c.customerID = c.customerID