更正查询中的JOIN

时间:2019-06-03 19:40:37

标签: mysql sql join

在低位查询中,如何显示“用户”表中的所有记录? 当前仅显示具有销售记录的商品

    SELECT
    d.operator_id as num_carteira,
    u.name_carteira as Carteira,
    sum(d.`value`) AS Valor,
    sum(d.`quantity`) AS Qtde
    FROM daily_productivity d
    RIGHT JOIN product p
    ON d.product_id = p.id
    RIGHT JOIN `user` u
    ON d.operator_id = u.id
    WHERE YEAR(date) = 2019 AND MONTH(date) = 06 AND d.daily_productivity_status_id = 2 AND p.mobilizador_id = 1 AND u.role_id = 6 
    ORDER BY u.name_carteira

2 个答案:

答案 0 :(得分:2)

您不应在where子句中使用左/右联接表列,而应将这些条件添加到相关的ON子句中

    SELECT
    d.operator_id as num_carteira,
    u.name_carteira as Carteira,
    sum(d.`value`) AS Valor,
    sum(d.`quantity`) AS Qtde
    FROM daily_productivity d
    LEFT  JOIN product p  ON d.product_id = p.id AND  p.mobilizador_id = 1 
    LEFT JOIN `user` u   ON d.operator_id = u.id AND  u.role_id = 6 
    WHERE YEAR(date) = 2019 AND MONTH(date) = 06 AND d.daily_productivity_status_id = 2 
    ORDER BY u.name_carteira

,您还应该使用正确的分组依据

    SELECT
    d.operator_id as num_carteira,
    u.name_carteira as Carteira,
    sum(d.`value`) AS Valor,
    sum(d.`quantity`) AS Qtde
    FROM daily_productivity d
    LEFT  JOIN product p  ON d.product_id = p.id AND  p.mobilizador_id = 1 
    LEFT JOIN `user` u   ON d.operator_id = u.id AND  u.role_id = 6 
    WHERE YEAR(date) = 2019 AND MONTH(date) = 06 AND d.daily_productivity_status_id = 2 
    GROUP BY d.operator_id as num_carteira,  u.name_carteira as Carteira,
    ORDER BY u.name_carteira

不允许在大多数数据库中(并且对于特定的数据库版本)使用不带分组依据的聚合功能,并且会引发错误

答案 1 :(得分:1)

使用left join,然后将表放在要保留所有行的第一位,即user。可以在where子句中过滤此表上的条件。

所有其他表的条件应放在on子句中:

SELECT d.operator_id as num_carteira, u.name_carteira as Carteira,
       sum(d.`value`) AS Valor, sum(d.`quantity`) AS Qtde
FROM user u LEFT JOIN
     daily_productivity d
     ON d.operator_id = u.id AND
        d.date >= '2019-06-01' AND
        d.date < '2019-07-01' AND
        d.daily_productivity_status_id = 2 LEFT JOIN
     product p
     ON d.product_id = p.id AND p.mobilizador_id = 1
WHERE u.role_id = 6 
GROUP BY d.operator_id, u.name_carteira 
ORDER BY u.name_carteira;

这猜测date来自daily_productivity表。

请注意,我更改了日期逻辑,因此它与索引更兼容。我还建议您在u.id中使用d.operator_id而不是SELECT,因为后者可能是NULL

实际上,如果您希望所有user中的用户,则删除where子句。