尝试写入mysql,它将显示约会的Appointment_duration,mechanic_Firstname,mechanic_lastname,customer_firstname和customer_lastname以及max&最短的时间,但我的代码给了我错误的结果..我只想要max&最小持续时间和相应的名称。所以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
答案 0 :(得分: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
如果所有机械师的名称和客户名称都列在firstname
和lastname
两栏中,您可以添加一个标记来标记客户的机制。
答案 1 :(得分: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);