0

我是 mysql 新手,编写了一个 My sql 查询并尝试使用两个子查询进行外部连接,但结果未显示准确的结果这里是查询

SELECT a.lpcode,a.lpname,a.companycode,a.zone,a.tdy_growr,a.tdy_acres,b.tdate_growr,tdate_acres,a.name
  FROM    (SELECT z.lpcode,
                  x.companycode,
                  z.lpname,
                  z.zone,
                  z.name,
                  count(x.vehicleno) tdy_growr,
                  sum(x.haulagecode) tdy_acres
             FROM gis.registration x, loadingpoint z
            WHERE x.date =
                     (SELECT max(a.date)
                        FROM gis.registration a
                       WHERE     a.fieldno > 0
                             AND a.haulagecode > 0
                             AND a.isaccepted = 1)
                  AND z.lpcode = x.lpcode
                  AND x.fieldno > 0
                  AND x.haulagecode > 0
                  AND x.isaccepted = 1
           GROUP BY x.lpcode) a
       RIGHT OUTER JOIN
          (SELECT r.lpcode,
                  count(r.vehicleno) tdate_growr,
                  sum(r.haulagecode) tdate_acres
             FROM gis.registration r, loadingpoint l
            WHERE r.fieldno > 0 AND r.haulagecode > 0 AND r.isaccepted = 1
            AND r.lpcode = l.lpcode
           GROUP BY l.lpcode) b
       ON a.lpcode = b.lpcode
ORDER BY a.zone, a.lpcode

任何帮助都可以提前感谢

4

1 回答 1

0

右外连接的性能很差,并且在很多情况下您不能更改查询的结构以使用左外连接来代替,这样性能会更好。您的查询正在做的是从 b 获取所有行,而不管 a 中是否有要加入的行。重写的相同查询是:

SELECT             a.lpcode,a.lpname,a.companycode,a.zone,a.tdy_growr,a.tdy_acres,b.tdate_growr,a.tdate_acres,a.name
FROM (SELECT r.lpcode,
              count(r.vehicleno) tdate_growr,
              sum(r.haulagecode) tdate_acres
         FROM gis.registration r, loadingpoint l
        WHERE r.fieldno > 0 AND r.haulagecode > 0 AND r.isaccepted = 1
        AND r.lpcode = l.lpcode
       GROUP BY l.lpcode) b
   LEFT OUTER JOIN (SELECT z.lpcode,
              x.companycode,
              z.lpname,
              z.zone,
              z.name,
              count(x.vehicleno) tdy_growr,
              sum(x.haulagecode) tdy_acres
         FROM gis.registration x, loadingpoint z
        WHERE x.date =
                 (SELECT max(a.date)
                    FROM gis.registration a
                   WHERE     a.fieldno > 0
                         AND a.haulagecode > 0
                         AND a.isaccepted = 1)
              AND z.lpcode = x.lpcode
              AND x.fieldno > 0
              AND x.haulagecode > 0
              AND x.isaccepted = 1
       GROUP BY x.lpcode) a
   ON a.lpcode = b.lpcode
ORDER BY a.zone, a.lpcode

这也给出了 b 中的所有行,而不管 a 中是否存在要加入的匹配行。

如果您的问题是您在所有这些列中都得到 NULLS:“a.lpcode,a.lpname,a.companycode,a.zone,a.tdy_growr,a.tdy_acres,a.tdate_acres,a.name”然后使用应该使用您已经在使用的结构,但使用 LEFT OUTER JOIN 代替,这可能会在此列“b.tdate_growr”中返回 null

于 2012-06-13T05:06:14.823 回答