有一个名为 books 的表,其结构如下:
╔════════════╦═══════════╦════════╗
║ LibraryId ║ BookId ║ Price ║
╠════════════╬═══════════╬════════╣
║ 123 ║ 9001 ║ 10.99 ║
║ 123 ║ 9005 ║ 12.99 ║
║ 123 ║ 9006 ║ 7.99 ║
║ 124 ║ 8012 ║ 6.49 ║
║ 124 ║ 9001 ║ 3.19 ║
║ 124 ║ 9076 ║ 7.39 ║
╚════════════╩═══════════╩════════╝
我怎么能做一个选择来返回完整的表格,但还有一个名为 Ordinal 的字段,它“计算”每个图书馆的书籍数量。结果应该类似于:
╔════════════╦═══════════╦════════╦════════╗
║ LibraryId ║ BookId ║ Price ║Ordinal ║
╠════════════╬═══════════╬════════╬════════╣
║ 123 ║ 9001 ║ 10.99 ║ 1 ║
║ 123 ║ 9005 ║ 12.99 ║ 2 ║
║ 123 ║ 9006 ║ 7.99 ║ 3 ║
║ 124 ║ 8012 ║ 6.49 ║ 1 ║
║ 124 ║ 9001 ║ 3.19 ║ 2 ║
║ 124 ║ 9076 ║ 7.39 ║ 3 ║
╚════════════╩═══════════╩════════╝════════╝
我试过类似的东西:
SET @var_record = 1;
SELECT *, (@var_record := @var_record + 1) AS Ordinal
FROM books;
但这将继续计数,而与 libraryId 无关。我需要一些可以在每次 libraryId 更改时重置序数的东西。我更喜欢单个查询而不是过程。
测试数据sql脚本:
create temporary table books(libraryId int, bookId int, price double(4,2));
insert into books (libraryId, bookId, price) values (123, 9001, 10.99),(123, 9005, 10.99),(123, 9006, 10.99),(124, 8001, 10.99),(124, 9001, 10.99),(124, 9076, 10.99);