将嵌套的MYSQL查询转换为一个视图查询

时间:2014-12-13 12:26:03

标签: mysql

我有以下表格:

CashiersInShifts(ShiftNun,ShiftDAte,CashierNum),
Oreders(OrderNum,Payment,CustomerNum,ShiftNum,ShiftDAte,CashierNum),
Course(CourseNum,Name,Price),
CourseInOrder(OrderNum,CourseNum,Quantity),
Employee(EmployeeNum,Name,BirthDay).

我想转换以下查询:

SELECT EmployeeNum, Name, MAX(TotalSales)/10 AS Commission
FROM (SELECT OrderNum, CS.ShiftDate, CS.CashierNum AS EmployeeNum, CO.CourseNum, C.Price, SUM(C.Price) AS TotalSales
FROM CashiersInShifts CS NATURAL JOIN Orders O NATURAL JOIN CoursesInOrder CO NATURAL JOIN Course C
WHERE CS.ShiftDate = DATE_SUB(CURDATE(),INTERVAL 1 DAY)
GROUP BY CS.CashierNum) T1 NATURAL JOIN Employee;

进入一个视图查询。 谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

您可以使用SELECT中的相关子查询执行此操作。我建议你不要使用natural join - 如果你想避免无意的错误,要知道你加入的列要好得多。但是,您的问题与您的查询有关,因此我将natural join留在:

SELECT e.EmployeeNum, e.Name, 
       (SELECT SUM(C.Price) AS TotalSales
        FROM CashiersInShifts CS NATURAL JOIN
             Orders O NATURAL JOIN
             CoursesInOrder CO NATURAL JOIN
             Course C
        WHERE CS.ShiftDate = DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND
              CS.CaashierNum = e.EmployeeNum
        ORDER BY TotalSales DESC
        LIMIT 1
       ) / 10 as Commission
FROM Employee e;

请注意,这将返回所有员工的行。如果您想将员工限制为收银员,可以添加HAVING Commission IS NOT NULL