MySQL-使用MIN进行分组无法正常工作

时间:2019-03-02 20:13:18

标签: sql group-by mysql-5.7

我有以下联合查询,其中我正在设置虚拟行号:


 await Vehicle.aggregate([{
    $lookup: {
      from: 'users', 
      localField: "driver_id", 
      foreignField: "_id", 
      as: "users"
    }
  }]).then(vehicles => {
    data.status   = 200;
    data.message  = "Vehicles retreived!";
    data.data     = vehicles;
  }).catch(err => {
    // console log value
    console.log(err);
    data.status   = 500;
    data.message  = "Error retreiving vehicle";
    data.data     = JSON.stringify(err);
  });


这将返回以下结果:

SELECT @row_num:=2 as row_num, id, name, admin1, admin3, admin4
  FROM locations
 WHERE feature_class IN ('P', 'A')
   AND name LIKE 'cornwall%'
UNION ALL      
SELECT @row_num:=1 as row_num, id, name, admin1, admin3, admin4
 FROM locations
WHERE feature_class = 'L' AND feature_code = 'RGN'
  AND name LIKE 'cornwall%'

现在,当我将此查询添加为子查询并使用MIN选择具有最低row_num的行时,我得到的结果不正确:

row_num   |   id       |     name    |   admin1   |   admin3   |  admin4  
-------------------------------------------------------------------------
   2      |   2652355  |   Cornwall  |   ENG      |            |          
   1      |   11609029 |   Cornwall  |   ENG      |            |         

我得到以下结果:

 SELECT MIN(t0.row_num), 
   t0.id,
   t0.name, 
   t4.name AS town_admin4,
   t3.name AS county_admin3, 
   t1.name AS admin1
  FROM (
           SELECT @row_num:=2 as row_num, id, name, admin1, admin3, admin4
            FROM locations
           WHERE feature_class IN ('P', 'A')
             AND name LIKE 'cornwall%'
           UNION ALL       
           SELECT @row_num:=1 as row_num , id, name, admin1, admin3, admin4
            FROM locations
           WHERE feature_class = 'L' AND feature_code = 'RGN'
             AND name LIKE 'cornwall%'
      ) t0
  LEFT JOIN locations t1 ON t1.admin1 = t0.admin1 AND t1.feature_code = 'ADM1'
  LEFT JOIN locations t3 ON t3.admin3 = t0.admin3 AND t3.feature_code = 'ADM3'
  LEFT JOIN locations t4 ON t4.admin4 = t0.admin4 AND t4.feature_code = 'ADM4'
  GROUP BY t0.name,
           t4.name,
           t3.name, 
           t1.name
  ORDER BY t0.name  

如您所见,以上内容是不正确的。第1行的记录应为ID 11609029

为什么会这样-MIN运算符为什么没有按预期工作?

0 个答案:

没有答案