使用派生表进行完全外连接 - mysql

时间:2013-11-20 03:20:18

标签: mysql sql join

我在两个表上使用完全外连接时遇到问题,我使用的sql如下:

SELECT
  a.sryear,
  b.reqyear,
  a.mid,
  b.description,
  sum(a.kmq + b.rmq) as sum 
FROM
  (select
    EXTRACT(YEAR 
  FROM
    t.date) AS srYear,
    m.materialid as mid,
    m.description,
    sum(km.quantity) as kmq 
  FROM
    kit k,
    kitmaterial km,
    materials m,
    service s,
    transaction t 
  WHERE
    t.serviceid=s.serviceid 
    AND s.kitid=k.kitid 
    AND k.kitid=km.kitid 
    AND km.materialid=m.materialid 
  GROUP BY
    srYear,
    m.materialid 
  ORDER BY
    srYear,
    m.materialid) as a FULL 
OUTER JOIN
  , (
    SELECT
      EXTRACT(YEAR 
    FROM
      r.datecreated) AS reqYear,
      m.materialid as mid,
      m.description as description,
      sum(rm.quantity) as rmq 
    FROM
      requisitionmaterial rm,
      materials m,
      requisition r 
    WHERE
      rm.materialid=m.materialid 
      AND r.requisitionid=rm.requisitionid 
    GROUP BY
      reqYear,
      m.materialid 
    ORDER BY
      reqYear,
      m.materialid
  ) as b 
    ON a.mid=b.mid 
    AND a.sryear=b.reqyear;

任何提供的协助都将受到赞赏。

谢谢!

1 个答案:

答案 0 :(得分:1)

在内联视图ab按预期工作的情况下,存在一个问题。

SELECT
  ....
  sum(a.kmq + b.rmq) as sum 

SUM()是聚合函数。所以没有GROUP BY就不能使用。你是说这个吗?

SELECT
  ....
  a.kmq + b.rmq as `sum`

否则,您应该使用GROUP BY和一些列