Mysql右外连接不起作用100%

时间:2012-06-13 04:29:14

标签: mysql sql

我是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

任何帮助可能会提前感谢

1 个答案:

答案 0 :(得分:0)

右外连接具有可怕的性能,并且没有太多情况下您无法更改查询结构以使用左外连接而不是更好。你的查询正在做的是获取b中的所有行,无论是否有一行要加入。重写的相同查询是:

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中的所有行,无论是否有一个匹配的行要加入。

如果您的问题是您在所有这些列中获得了NULLS:" a.lpcode,a.lpname,a.companycode,a.zone,a.tdy_growr,a.tdy_acres,a.tdate_acres, a.name"然后使用应该使用你已经使用的结构,但使用LEFT OUTER JOIN而不是在此列中返回null" b.tdate_growr"

相关问题