当我使用 FIND_IN_SET、GROUP BY 和 COUNT(*) 将另一个元素添加到集合中时,为什么 MySQL 返回不同的查询计数

问题描述 投票:0回答:1

我有一个 MySQL 查询来获取设备及其位置的摘要:

SELECT `devicetypes`.`permanentslug`,
   `devices`.`yearmanufactured`,
   `engagements`.`name` AS `location`,
   Count(*) AS `count`
FROM `devices`
   INNER JOIN `devicemodels`
           ON `devicemodels`.`id` = `devices`.`devicemodelid`
   INNER JOIN `devicetypes`
           ON `devicetypes`.`id` = `devicemodels`.`devicetypeid`
   INNER JOIN `locations`
           ON `locations`.`id` = `devices`.`locationid`
   INNER JOIN `engagements`
           ON `engagements`.`id` = `locations`.`engagementid`
WHERE  `devices`.`deletedat` IS NULL
   AND `devicemodels`.`deletedat` IS NULL
   AND `devicetypes`.`deletedat` IS NULL
   AND `locations`.`deletedat` IS NULL
   AND `engagements`.`deletedat` IS NULL
   AND Find_in_set(`locations`.`engagementid`, '224,286') > 0
GROUP  BY `devicetypes`.`permanentslug`,
      `locations`.`name`,
      `devices`.`yearmanufactured`
ORDER  BY `devicetypes`.`permanentslug` ASC,
      `engagements`.`name` ASC; 

当我运行此命令时,我得到以下结果:

永久鼻塞 制造年份 地点
除颤 诊所 1
除颤 诊所 1
除颤 2012 诊所 1
除颤 2020 医院 2
除颤 医院 1

这有点准确,但奇怪的是它没有合并前两行并给我该行的计数为 2。但是,当我将另一个元素添加到数组中时,我使用 FIND_IN_SET 检查,得到的结果不准确。这是仅将 223 添加到 Find_in_set 行的新查询:

SELECT `devicetypes`.`permanentslug`,
   `devices`.`yearmanufactured`,
   `engagements`.`name` AS `location`,
   Count(*) AS `count`
FROM `devices`
   INNER JOIN `devicemodels`
           ON `devicemodels`.`id` = `devices`.`devicemodelid`
   INNER JOIN `devicetypes`
           ON `devicetypes`.`id` = `devicemodels`.`devicetypeid`
   INNER JOIN `locations`
           ON `locations`.`id` = `devices`.`locationid`
   INNER JOIN `engagements`
           ON `engagements`.`id` = `locations`.`engagementid`
WHERE  `devices`.`deletedat` IS NULL
   AND `devicemodels`.`deletedat` IS NULL
   AND `devicetypes`.`deletedat` IS NULL
   AND `locations`.`deletedat` IS NULL
   AND `engagements`.`deletedat` IS NULL
   AND Find_in_set(`locations`.`engagementid`, '223,224,286') > 0
GROUP  BY `devicetypes`.`permanentslug`,
      `locations`.`name`,
      `devices`.`yearmanufactured`
ORDER  BY `devicetypes`.`permanentslug` ASC,
      `engagements`.`name` ASC; 

结果如下:

永久鼻塞 制造年份 地点
除颤 诊所 1
除颤 2012 诊所 1
除颤 2020 医院 2
除颤 医院 1
除颤 2015 溪边 7
除颤 2019 溪边 4
除颤 溪畔 9

所以,现在它完全删除了一个空诊所行,但它没有将其计数与另一行组合在一起。总体来说很奇怪。这可能是 FIND_IN_SET 的问题吗?我以前从未见过 MySQL 出现这样的错误计数。

mysql group-by find-in-set
1个回答
0
投票

我知道这一定是我的 SQL 查询中的一些愚蠢错误,而且确实如此。查询底部的 GROUP BY 按

locations.name
进行分组,但是我随后在结果中显示
engagements.name AS location

当我将 GROUP BY 更改为

GROUP BY DeviceTypes.permanentslug, Engagements.name, Devices.yearManufactured

它解决了一切。希望在我弄清楚之前没有人花时间阅读所有这些。

© www.soinside.com 2019 - 2024. All rights reserved.