0

我有一个数据库,其中所有内容都使用start_dateend_date

我想要做的是动态获取一行的版本号。

因此,获取按 start_date 排序的具有特定 item_id 的所有行,然后给出 astart_date并将end_date其隔离为一行。我想要的是找出那一排的位置。

例如数据

id | item_id | start_date
1  | 1       | 01-31-2012
2  | 1       | 02-31-2012
3  | 2       | 02-31-2012
4  | 1       | 03-31-2012
5  | 2       | 05-31-2012
6  | 1       | 04-31-2012

如果使用select id from items where item_id = 2 and start_date = 05-31-2012

会返回5,所以我想要的版本是2

如果使用select id from items where item_id = 1 and start_date = 03-31-2012

会返回4,所以我想要的版本是3

我能想到的唯一方法是选择所有带有 item_id 的行,然后遍历每个项目检查 start_date,如果它不是我想要的,将 version_number 增加 1。

有没有办法只用mysql?

4

2 回答 2

2
SELECT COUNT(*) version
FROM items
WHERE item_id = 2 AND start_date <= '2012-05-31'

id <= 5代替日期比较(假设id是唯一的并且单调增长)

于 2012-11-20T23:54:03.533 回答
0

这个在 oracle 中工作..在内部选择查询中使用分析函数 row_number() 如下

select version from (select row_number() over ( partition by item_id  order by start_date ) version,item.* from item) where start_date ='05-31-2012'
于 2012-11-21T01:10:03.973 回答