同样的sql查询结果不一样?

时间:2017-07-18 20:09:04

标签: mysql sql

我有这个Sql查询

SELECT tt.ID_Partenaire, tt.Nom_Societe,tt.Image_Societe, tt.id_activite 
                FROM affiliate AS a 
                RIGHT JOIN 
                  (SELECT partenaires.ID_Partenaire, 
                  partenaires.Nom_Societe, partenaires.Image_Societe, partenaires.id_activite,
                        IFNULL(SUM(c.montant_real),0) AS mt1 
                    FROM partenaires
                        LEFT JOIN commande AS c 
                    ON partenaires.ID_Partenaire=c.id_partenaire 
                    GROUP BY partenaires.ID_Partenaire 
                  )AS tt 
            ON a.id_partenaire= tt.ID_Partenaire 
            GROUP BY tt.ID_Partenaire 
            ORDER BY (IFNULL(SUM(a.montat),0) + mt1) DESC 
            LIMIT 20

我有两台服务器:

  1. Version du serveur:5.7.11-log - MySQL社区服务器(GPL) - 本地 -
  2. 服务器版本:10.1.25-MariaDB-1~jessie - mariadb.org二进制发布 - 主机 -
  3. 当我在这些服务器上执行它时,每个服务器都会给我一个不同的结果。

    我认为问题出在ORDER BY

    作为我做出的解决方案:

    SELECT ID_Partenaire, Nom_Societe, Image_Societe, id_activite 
          FROM (SELECT tt.ID_Partenaire, tt.Nom_Societe,tt.Image_Societe, 
                 tt.id_activite, 
                 (IFNULL(SUM(a.montat),0) + mt1) as mm
                    FROM affiliate AS a 
                    RIGHT JOIN 
                      (SELECT partenaires.ID_Partenaire, 
                           partenaires.Nom_Societe, partenaires.Image_Societe, 
                           partenaires.id_activite,
                            IFNULL(SUM(c.montant_real),0) AS mt1 
                        FROM partenaires
                            LEFT JOIN commande AS c 
                        ON partenaires.ID_Partenaire=c.id_partenaire 
                        GROUP BY partenaires.ID_Partenaire 
                      )AS tt 
                ON a.id_partenaire= tt.ID_Partenaire 
                GROUP BY tt.ID_Partenaire 
                ORDER BY mm DESC 
                LIMIT 20) AS k
    

    我真的很困惑,因为MySql没有给我任何错误,但给出了不同的结果,我有其他疑问,我担心他也在为他们做同样的事情!

2 个答案:

答案 0 :(得分:0)

您可以使用explain report找到差异。只需运行explain extended SELECT ID_Partenaire, Nom_Societe...

答案 1 :(得分:0)

按顺序添加限制。 '限制'和'按顺序排列是在同一水平'限制'在'命令之前完成发生了,所以给出不同的结果

尝试这样的事情

SELECT ID_Partenaire,
  Nom_Societe,
  Image_Societe,
  id_activite
FROM
  (SELECT tt.ID_Partenaire,
    tt.Nom_Societe,
    tt.Image_Societe,
    tt.id_activite,
    (IFNULL(SUM(a.montat),0) + mt1) AS mm
  FROM affiliate                    AS a
  RIGHT JOIN
    (SELECT partenaires.ID_Partenaire,
      partenaires.Nom_Societe,
      partenaires.Image_Societe,
      partenaires.id_activite,
      IFNULL(SUM(c.montant_real),0) AS mt1
    FROM partenaires
    LEFT JOIN commande AS c
    ON partenaires.ID_Partenaire=c.id_partenaire
    GROUP BY partenaires.ID_Partenaire
    )AS tt ON a.id_partenaire= tt.ID_Partenaire
  GROUP BY tt.ID_Partenaire
  ORDER BY mm DESC
  ) AS k LIMIT 20