选择有很多表

时间:2017-07-08 18:14:41

标签: mysql select count sum left-join

我正在尝试查询销售报告,其中将显示销售代码,日期,产品数量(仅限),门票数量,总销售额以及员工的数量名称。 Click here to see the connection between the tables 查询我正在使用哪个不会返回错误但只返回一行,即使Sales表上没有任何内容,或者即使它已经满了它们

select sales.codv
, customers.name as customers
, concat(day(datav),'/',month(datav),'/',year(datav)) as date
, sum(prod_sal.amount) as 'products'
, count(tickets.codb) as 'tickets'
, sum(ifnull(products.preco,0) * ifnull(prod_sal.amount,0) + 
ifnull(tickets.price,0)) as 'total/€'
, employees.nome as employee
from sales
LEFT JOIN customers ON customers.codc=sales.codc
INNER JOIN employees ON employees.codf=sales.codf
LEFT JOIN prod_sal ON prod_sal.codv=sales.codv
LEFT JOIN products ON products.codp=prod_sal.codp
LEFT JOIN tickets ON tickets.codv=sales.codv

注意:datav是销售日期

1 个答案:

答案 0 :(得分:0)

如果您不使用group by子句,MySQL将假定您要聚合与where子句匹配的所有行。由于您没有where子句,这就是数据库中的所有内容。

select 
  sales.codv
  , customers.name as customers
  , concat(day(datav),'/',month(datav),'/',year(datav)) as date
  , sum(prod_sal.amount) as 'products'
  , count(tickets.codb) as 'tickets'
  , sum(ifnull(products.preco,0) * ifnull(prod_sal.amount,0) + ifnull(tickets.price,0)) as 'total/€'
  , employees.nome as employee
from 
  sales
  LEFT JOIN customers 
    ON customers.codc=sales.codc
  INNER JOIN employees 
    ON employees.codf=sales.codf
  LEFT JOIN prod_sal 
    ON prod_sal.codv=sales.codv
  LEFT JOIN products 
    ON products.codp=prod_sal.codp
  LEFT JOIN tickets 
    ON tickets.codv=sales.codv
group by
  sales.codv
  , customers.name
  ,  concat(day(datav),'/',month(datav),'/',year(datav)) as date