2013-03-25 64 views
0

試圖寫入MySQL將顯示Appointment_duration,mechanic_Firstname,mechanic_lastname,customer_firstname和customer_lastname約會的最大時間爲&,但我的代碼給我錯誤的結果..我只只需要最短的持續時間和相應的名稱。所以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 
+2

你可以提供樣本記錄嗎? – 2013-03-25 06:25:56

+0

包括預約表, – 2013-03-25 06:42:07

回答

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); 
1

的問題是,有兩個表customermechanic沒有關係,你必須單獨獲得最大和最小持續時間爲每個表和使用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上市,你可以添加標記來標記來自客戶的機制。