如何创建包含以下表格的视图?

时间:2017-12-30 11:38:59

标签: mysql join view sum

我有以下2 tables involved,我正在尝试create a view popularProducts,其中sum of each product's quantityOrdered等于或高于100.

我尝试了以下内容,但对我来说看起来并不合适:

SELECT productCode, productName, buyPrice, image FROM products JOIN orderDetails on products.productCode=orderDetails.products_productCode WHERE (SELECT SUM(quantityOrdered) >= 100);

OrderDetails表:

CREATE TABLE `orderDetails` (
  `products_productCode` bigint(20) UNSIGNED NOT NULL,
  `orders_orderNumber` bigint(20) UNSIGNED NOT NULL,
  `quantityOrdered` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

products表:

CREATE TABLE `products` (
  `productCode` bigint(20) UNSIGNED NOT NULL,
  `productName` varchar(45) DEFAULT NULL,
  `productDescription` text,
  `quantityInStock` smallint(5) UNSIGNED DEFAULT NULL,
  `buyPrice` decimal(7,2) UNSIGNED DEFAULT NULL,
  `image` varchar(45) DEFAULT NULL
) E

1 个答案:

答案 0 :(得分:1)

您需要group by和having子句来订购数量总和

CREATE VIEW viewName AS
SELECT p.productCode, p.productName, p.buyPrice, p.image 
FROM products p
JOIN orderDetails o on p.productCode=o.products_productCode 
GROUP BY p.productCode, p.productName, p.buyPrice, p.image 
HAVING SUM(o.quantityOrdered) >= 100