在不使用某些函数的情况下组合两个查询

时间:2017-06-06 18:11:14

标签: php mysql sql

我有两个单独的查询:

SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
  SUM(prestavkaDoch) as presDoch,
  operatorDoch 
  FROM dochazkaVyroba 
    WHERE operatorDoch IN ("x","y","z")
    AND datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch;

SELECT SUM(CAS) as cisloVyk,
  JMENO 
  FROM produkce 
    WHERE JMENO IN ("x","y","z")
    AND DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO;

我希望将这些组合成一个查询。

并单独得到以下结果:

cisloDoch presDoch operatorDoch
 57600      60         x
  0         0          y
 57600      0          z


cisloVyk JMENO 
 532       x
  0        y
 780       z

我要做的是将上述查询合并为一个,基于:

produkce.JMENO = dochazkaVyroba.operatorDoch

所以我得到了以下内容:

cisloDoch presDoch operatorDoch  cisloVyk JMENO 
 57600      60         x             532    x
  0         0          y               0    y
 57600      0          z              780   z

不幸的是FULL OUTER JOIN在MySQL中无法使用。

我也无法将UNIONON produkce.JMENO = dochazkaVyroba.operatorDoch一起使用。

2 个答案:

答案 0 :(得分:0)

蛮力方式就是加入两个子查询:

SELECT
    t1.cisloDoch,
    t1.presDoch,
    t1.operatorDoch,
    t2.cisloVyk,
    t2.JMENO
FROM
(
    SELECT
        TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch, 
        SUM(prestavkaDoch) AS presDoch,
        operatorDoch 
    FROM dochazkaVyroba 
    WHERE operatorDoch IN ("x","y","z") AND
          datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch
) t1
INNER JOIN
(
    SELECT SUM(CAS) as cisloVyk, JMENO 
    FROM produkce 
    WHERE JMENO IN ("x","y","z") AND
          DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO
) t2
    ON t1.operatorDoch = t2.JMENO

答案 1 :(得分:0)

您可以使用union allgroup by

SELECT MAX(cisloDoch) as cisloDoch,
       MAX(presDoch) as presDoch,
       MAX(operatorDoch) as operatorDoch,
       MAX(cisloVyk) as cisloVyk,
       MAX(JMENO) as JMENO
FROM ((SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch, 
              SUM(prestavkaDoch) as presDoch, operatorDoch,
              NULL as cisloVyk, NULL as JMENO
       FROM dochazkaVyroba 
       WHERE operatorDoch IN ('x', 'y', 'z') AND
             datumDoch BETWEEN '2017-06-01' AND '2017-06-02'
       GROUP BY operatorDoch
      ) UNION ALL
      (SELECT NULL NULL, NULL, SUM(CAS) as cisloVyk, JMENO 
       FROM produkce 
       WHERE JMENO IN ('x', 'y', 'z') AND
             datum BETWEEN '2017-06-01' AND '2017-06-02'
       GROUP BY JMENO
      )
     ) op
GROUP BY COALESCE(operatorDoch, JMENO);