Mysql复杂从4个表中选择查询

时间:2017-05-30 14:36:22

标签: mysql

我研究了近200个关于mysql复杂查询的示例页面,但仍然坚持使用。

这是我的结构

from scipy import misc
# ...
# Do OP operations
misc.imshow(resized_image)

是否可以仅使用查询获得以下输出?

Table name: zones

zoneId | zoneName
------------------

Table name: customers

customesId | zoneId | customerName
----------------------------------

Table name: products

productId | productName
-----------------------

Table name: sales

sid | zoneId | customerId | productId | amount
----------------------------------------------

即使客户或产品没有销售,我想得到“0”

我试过了:

zoneName | customerName | productName   | amount(SUM)
---------------------------------------------------
ZoneX    | customerA    | productName_1 | 10
         |              | productName_2 | 0
         |              | productName_3 | 4
         |              | productName_4 | 0
ZoneX    | customerB    | productName_1 | 7
         |              | productName_2 | 0
         |              | productName_3 | 4
         |              | productName_4 | 3
.......

2 个答案:

答案 0 :(得分:2)

您需要将所有客户交叉加入产品,以便每个客户都列出所有产品,无论销售情况如何。

SELECT z.zoneName
     , c.customerName
     , p.productName
     , SUM(coalesce(s.amount,0)) AS amount 
FROM customers c
INNER JOIN zones z 
  ON c.zoneId = z.zoneId 
CROSS JOIN PRODUCTS P
LEFT JOIN sales S
  ON c.customerId = s.customerId
 and s.productID = p.productID 
GROUP BY z.zoneName
       , c.customerName
       , p.productName

答案 1 :(得分:0)

您可以尝试此查询

SELECT c.zoneId ,c.customesId ,c.customerName,IF(s.amount IS NULL, 0 , s.amount) 
FROM customers AS c, products AS p
LEFT JOIN sales AS s ON s.productId  = p.productId  and s.customersid = c.customersid

希望这有帮助。