INSERT INTO products(product_name, price)VALUES('iPhone', 699), ('iPad',599), ('Macbook Pro',1299);INSERT INTO stores(store_name)VALUES('North'), ('South');INSERT INTO sales(store_id,product_id,quantity,sales_date)VALUES(1,1,20,'2017-01-02'), (1,2,15,'2017-01-05'), (1,3,25,'2017-01-05'), (2,1,30,'2017-01-02'), (2,2,35,'2017-01-05');
要获得每个商店和每个产品的总销售额,您可以计算销售额,并按商店和产品分组如下:
SELECT store_name, product_name,SUM(quantity * price) AS revenueFROM salesINNER JOIN products ON products.id = sales.product_idINNER JOIN stores ON stores.id = sales.store_idGROUP BY store_name , product_name;
执行上面查询,得到以下结果 -
mysql>SELECT store_name, product_name,SUM(quantity * price) AS revenueFROM salesINNER JOIN products ON products.id = sales.product_idINNER JOIN stores ON stores.id = sales.store_idGROUP BY store_name , product_name; +------------+--------------+------------+| store_name | product_name | revenue |+------------+--------------+------------+| North | iPad | 8985.0000 || North | iPhone | 13980.0000 || North | Macbook Pro | 32475.0000 || South | iPad | 20965.0000 || South | iPhone | 20970.0000 |+------------+--------------+------------+5rowsinset
现在,如果你想知道哪个商店中的哪些产品的没有销售怎么办? 上面的查询无法回答这个问题。
要解决这个问题,可以使用CROSS JOIN子句。
首先,使用CROSS JOIN子句来获取所有商店和产品的组合:
SELECT store_name, product_nameFROM stores AS aCROSS JOIN products AS b;
执行上面查询语句,得到以下结果 -
mysql>SELECT store_name, product_nameFROM stores AS aCROSS JOIN products AS b;+------------+--------------+| store_name | product_name |+------------+--------------+| North | iPhone || South | iPhone || North | iPad || South | iPad || North | Macbook Pro || South | Macbook Pro |+------------+--------------+6rowsinset
接下来,将上述查询的结果与按商店和产品返回总销售额的查询相结合。以下查询说明了这个想法:
SELECT b.store_name, a.product_name,IFNULL(c.revenue, 0) AS revenueFROM products AS aCROSS JOIN stores AS bLEFT JOIN (SELECT stores.id AS store_id, products.id AS product_id, store_name, product_name,ROUND(SUM(quantity * price), 0) AS revenueFROM salesINNER JOIN products ON products.id = sales.product_idINNER JOIN stores ON stores.id = sales.store_idGROUP BY store_name , product_name) AS c ON c.store_id = b.idAND c.product_id= a.idORDER BY b.store_name;