小编mar*_*net的帖子

为什么我从查询和视图中得到不同的结果

我面临的基本问题是我需要每个项目的最新记录。

一些设置... MySQL 5.6.14。

我需要创建两个视图(因为 MySQL 不允许我在视图中有子查询)。我的第一个查询设置了这样的数据。

select 
    `inventoryrecords`.`inventoryrecordid` AS `inventoryrecordid`,
    `inventoryrecords`.`logicaldeviceid` AS `logicaldeviceid`,
    `inventoryrecords`.`passrfid` AS `passrfid`,
    `inventoryrecords`.`tagepc` AS `tagepc`,
    `inventoryrecords`.`currentstate` AS `currentstate`,
    `inventoryrecords`.`statedateutc` AS `statedateutc`,
    `inventoryrecords`.`ownerobjectid` AS `ownerobjectid`,
    `inventoryrecords`.`ownerobjecttype` AS `ownerobjecttype`
from
    `inventoryrecords`
where
    1
order by `inventoryrecords`.`statedateutc` desc
Run Code Online (Sandbox Code Playgroud)

然后我可以使用我的“真实”查询将所有内容限制为每个 TagEPC 的最后一条记录。

select 
    `lastinventoryrecords_step1`.`inventoryrecordid` AS `inventoryrecordid`,
    `lastinventoryrecords_step1`.`logicaldeviceid` AS `logicaldeviceid`,
    `lastinventoryrecords_step1`.`passrfid` AS `passrfid`,
    `lastinventoryrecords_step1`.`tagepc` AS `tagepc`,
    `lastinventoryrecords_step1`.`currentstate` AS `currentstate`,
    `lastinventoryrecords_step1`.`statedateutc` AS `statedateutc`,
    `lastinventoryrecords_step1`.`ownerobjectid` AS `ownerobjectid`,
    `lastinventoryrecords_step1`.`ownerobjecttype` AS `ownerobjecttype`
from
    `lastinventoryrecords_step1`
group by `lastinventoryrecords_step1`.`tagepc`
order by `lastinventoryrecords_step1`.`statedateutc` desc
Run Code Online (Sandbox Code Playgroud)

当我尝试从“真实”视图中选择 * 时,我没有得到我期望的数据。但是,当我在窗口中使用子查询运行查询时。 …

mysql view group-by greatest-n-per-group

2
推荐指数
1
解决办法
1943
查看次数

标签 统计

greatest-n-per-group ×1

group-by ×1

mysql ×1

view ×1