简体   繁体   中英

count,sum on both main table(union) and its left table in mysql

SELECT pa.prid,pa.prodid,pa.prva, ps.psna,ps.psnamid,ps.psval 
    FROM ( SELECT pid,prodid,count(prodid) as prid , 
          sum(prval) as prva
          FROM prodarpa 
          WHERE fcl = 1  GROUP BY prodid
    UNION SELECT pid,prodid,count(prodid) as prid , 
          sum(prval) as prva
          FROM prodarpb 
          WHERE fcl = 1  GROUP BY prodid ) AS pa 
    LEFT JOIN (SELECT psid,psnamid,count(psnamid) as psna,SUM(psvalue) as psval 
               FROM prosection GROUP BY psnamid ) AS ps
               ON ( pa.pid = ps.psid ) 

Hence i want result as below :

pa.prid | pa.prodid | pa.prva | ps.psna | ps.psnamid | ps.psval 
 193        3           300      193         2          499
 200        5           100       0          0           0
  0         0            0       201         8          300
 163        10          678      163         5          453

What i mean is if pa.prid value is not in ps.psna then it should show 0 value in each column of ps table and same on another way

but its not happening

Without data to work from this is guesswork.

SELECT
      pa.prid
    , pa.prodid
    , pa.prva
    , ps.psna
    , ps.psnamid
    , ps.psval
FROM (
      SELECT
            pid
          , prodid
          , COUNT(prodid) AS prid
          , SUM(prval) AS prva
      FROM (
            SELECT
                  pid
                , prodid
                , prval
            FROM prodarpa
            WHERE fcl = 1
            UNION ALL
                  SELECT
                        pid
                      , prodid
                      , prval
                  FROM prodarpb
                  WHERE fcl = 1
            ) AS s
      GROUP BY
            pid
          , prodid
      ) AS pa
      LEFT JOIN (
            SELECT
                  psid
                , psnamid
                , COUNT(psnamid) AS psna
                , SUM(psvalue) AS psval
            FROM prosection
            GROUP BY
                  psid
                , psnamid
      ) AS ps ON (pa.pid = ps.psid)

Take care when using group by that you always specify ALL non-aggregating columns . MySQL does provide for a syntax where this isn't required - however the results of using that syntax are not reliable, and the syntax is only allowed if ONLY_FULL_GROUP_BY is enabled.

see: https://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM