MySQL多表操作是數據庫開發中常見的應用場景。掌握多表操作可以提高開發效率和數據管理能力。以下是一些MySQL多表操作的試題。
1. 查找所有訂單中商品數量大于等于2個的訂單信息,包括訂單編號、訂單日期、客戶名稱、商品名稱、商品數量。
SELECT Orders.OrderID,Orders.OrderDate,Customers.CustomerName,Products.ProductName,OrderDetails.Quantity FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID JOIN Products ON OrderDetails.ProductID = Products.ProductID WHERE OrderDetails.Quantity >= 2;
2. 查找所有訂單中的客戶名稱和訂單數量,按訂單數量從多到少排序。
SELECT Customers.CustomerName,COUNT(Orders.OrderID) AS OrderCount FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CustomerName ORDER BY OrderCount DESC;
3. 查找所有未被訂購過的商品名稱。
SELECT Products.ProductName FROM Products LEFT JOIN OrderDetails ON Products.ProductID = OrderDetails.ProductID WHERE OrderDetails.OrderID IS NULL;
4. 查找所有有優惠券的訂單的訂單日期、客戶名稱、訂單總金額。
SELECT Orders.OrderDate,Customers.CustomerName,SUM(OrderDetails.UnitPrice * OrderDetails.Quantity * (1 - OrderDetails.Discount)) AS TotalAmount FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID WHERE Orders.Coupon<>'' GROUP BY Orders.OrderID;
5. 查找所有有訂單的城市中,訂單總金額最高的城市名稱和訂單總金額。
SELECT Customers.City,SUM(OrderDetails.UnitPrice * OrderDetails.Quantity * (1 - OrderDetails.Discount)) AS TotalAmount FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID GROUP BY Customers.City ORDER BY TotalAmount DESC LIMIT 1;
在實際開發中,多表操作是復雜數據管理的有效手段。以上試題只是冰山一角,希望能為你提供啟示。