0

试图在 mysql 中编写将显示约会的约会时间、技工名字、技工名字、客户名字和顾客名字,但我的代码给了我错误的结果。我只想要最大和最小持续时间和相应的名称。所以2行

SELECT 
Min(Appointment.Appointment_duration) AS MINOfAppointment_duration, 
Max(Appointment.Appointment_duration) AS MAXOfAppointment_duration,
mechanic_Firstname, mechanic_lastname, customer_firstname, customer_lastname
FROM Appointment, mechanic, Customer
WHERE (mechanic.mechanic_ID=Appointment.mechanic_ID) AND (customer.customer_ID=Appointment.customer_ID);

约会表中的记录

Appointment_ID  Appointment_DATE    Appointment_Duration    Mechanic_ID Customer_ID
12               08/01/2007     0:35:00                      1            5684
13               01/01/2009     2:15:36                      6            2534
14               06/12/2010     0:05:29                      7            7423
4

2 回答 2

1

customer问题是,两个表之间没有关系mechanic,您必须分别获取每个表的最大和最小持续时间,并使用UNION ALL将两个结果集合并为一个。就像是:

SELECT 
  m.mechanic_Firstname AS FirstName, 
  m.mechanic_lastname AS LastName,
  IFNULL(Min(a.Appointment_duration), 0) AS MINOfAppointment_duration, 
  IFNULL(Max(a.Appointment_duration), 0) AS MAXOfAppointment_duration
FROM mechanic AS m
LEFT JOIN Appointment AS a ON a.mechanic_ID = m.mechanic_ID
GROUP BY m.mechanic_Firstname,
         m.mechanic_lastname
UNION ALL
SELECT 
  c.customer_firstname,
  c.customer_lastname,
  IFNULL(Min(a.Appointment_duration), 0), 
  IFNULL(Max(a.Appointment_duration), 0)
FROM customer AS c
LEFT JOIN Appointment AS a ON a.mechanic_ID = c.customer_ID
GROUP BY c.customer_firstname,
         c.customer_lastname;

这只会给你四列:

FirstName  |  LastName  |  MINOfAppointment_duration  |  MAXOfAppointment_duration

在所有技工名称和客户名称都列在两列中的情况下firstnamelastname您可以添加一个标志来标记来自客户的技工。

于 2013-03-25T06:46:53.217 回答
0

您可以使用Union all函数来找出最大值和最小值。

    SELECT 
    Min(Appointment.Appointment_duration) AS Appointment_duration, 'Min' as status,
    mechanic_Firstname, mechanic_lastname, customer_firstname, customer_lastname
    FROM Appointment, mechanic, Customer
    WHERE (mechanic.mechanic_ID=Appointment.mechanic_ID) 
    AND (customer.customer_ID=Appointment.customer_ID);
Union all
    SELECT  
    Max(Appointment.Appointment_duration) AS  Appointment_duration,'Max' as status,
    mechanic_Firstname, mechanic_lastname, customer_firstname, customer_lastname
    FROM Appointment, mechanic, Customer
    WHERE (mechanic.mechanic_ID=Appointment.mechanic_ID)
    AND (customer.customer_ID=Appointment.customer_ID);
于 2013-03-25T06:43:14.360 回答