MySql从查询中获取第一个和最后一个结果

时间:2019-04-16 21:40:48

标签: mysql sql

我正在数据库中创建一些文档记录,每个文档可以有多个版本。每个新版本都是数据库中的新记录。要将文档版本分组在一起,我为它们分配了一个共享的唯一ID groupId

我要从数据库中获取的是最新的文档版本,但我也希望在日期创建原始文档:

documents table
- id
- group_id
- version
- created_at

示例记录:

id: 1, group_id: 'xyz', version: 1, created_at: date
id: 2, group_id: 'xyz', version: 2, created_at: date
id: 3, group_id: 'xyz', version: 3, created_at: date
etc...

我当时想使用不重复或按顺序排列,然后在查询中添加限制1以获得1个结果:

SELECT * FROM documents 
WHERE group_id='xyz'
ORDER BY 'created_at' DESC
LIMIT 1

但是除了(或代替最新版本的)created_at日期之外,我还如何包括原始文档的created_at日期?

我知道我可以使用ORDER BY 'created_at' ASC LIMIT 1重新运行查询,但是有一种方法可以在1个查询中完成所有操作吗?

5 个答案:

答案 0 :(得分:4)

您可以使用子查询:

SELECT * FROM documents 
WHERE id in (
    select min(id) FROM documents WHERE group_id='xyz'
    union
    select max(id) FROM documents WHERE group_id='xyz'
)

答案 1 :(得分:0)

添加子查询以查询原始广告的CREATED_AT是可行的:

select id, group_id, created_at, (select min(created_at) from documents d2 where 
d2.group_id = d.group_id)
from documents d
where group_id = 'xyz'
order by created_at desc
limit 1 

由于原始文档的CREATED_AT日期没有更改,因此我建议您对该数据进行非规范化,并添加一个新列ORIGINAL_CREATED_AT,该列用于所有新行。

答案 2 :(得分:0)

SELECT MIN(created_at) AS date_created, MAX(created_at) AS date_updated, group_id FROM documents WHERE group_id = 'xyz' GROUP BY group_id

答案 3 :(得分:0)

如果这是一个团体,我会去:

const reducer = (state, newState) => ({ ...state, ...newState });
const [state, setState] = useReducer(reducer, {
    filterStatus : 'ALL'
});

const performSearch = () => {
  console.log(state.filterStatus) //<= first time is ALL, second time same value ALL, third, is another value
}

useEffect(() => {
   performSearch()
},[])

<Select             
     onChange={(e) => {
        const {value} = e.target                
        setState({filterStatus:value})
        performSearch()            
      }}
      items={[{key:"ALL",value:"ALL"},{key:"ANOTHER",value:"ANOTHER"}]}
/>

尤其是,这可以利用select lastd.*, (select min(d2.created_at) from documents d2 where d2.group_id = d.group_id ) as first_created_at from (select d.* from documents d where group_id = 'xyz' order by created_at desc limit 1 ) lastd; 上的索引。

答案 4 :(得分:0)

此查询:

documents(group_id, created_at)

给出所有包含select d.* from documents d inner join ( select group_id, min(created_at) mindate, max(created_at) maxdate from documents group by group_id ) g on d.group_id = g.group_id and (d.created_at in (g.mindate, g.maxdate)) 的最小值和最大值created_at的所有行。
您可以添加所需的任何条件,例如:

group_id