sql - PostgreSQL:创建一系列唯一的数字以供参考
问题描述
我举了一个例子: http ://sqlfiddle.com/#!17/0f948/9
一对多是我正在构建的,尽管对于这个例子来说多对多会更真实。
我需要完成的工作:我应该能够为作者表中的作者顺序列生成描述整数序列的作者顺序,从数字 1 开始,以便每个数字在书籍参考中都是唯一的。因此,对于在特定书籍参考下设置的每个作者,数字从 1 到 2,到 3 等。还应生成 authororder 的数字以反映 author.fullname 的顺序(如:'select * from author order by fullname ')。
我尝试使用序列,但并没有像我希望的那样重置每本书的序列号,而是继续增加(我应该猜到的)。我也尝试在 row_number() 的帮助下执行此操作,但无法准备一个可以实现我想要的脚本。
生成 authororder 后的最终结果是这样的:
author_id fullname mobileno fk_book_id authororder
100 John Green 30303 1 (1)
101 Maureen Johnson 4343 1 (3)
102 Lauren Myracle 76665 1 (2)
103 Greg Mortenson 6434 2 (2)
104 David Oliver Relin 72322 2 (1)
105 Marco Polo 54321 3 (3)
106 Angus MacGyver 27234 3 (1)
107 Timo TA 83451 3 (4)
108 Anonymous 55554 3 (2)
解决方案
你似乎想要:
row_number() over (partition by fk_book_id order by fullname) as authororder
您可以将其合并到更新中:
update author a
set authororder = new_authororder
from (select a.*,
row_number() over (partition by fk_book_id order by fullname) as new_authororder
from author a
) aa
where a.authorid = aa.authorid;
推荐阅读
- stm32 - IAR Workbench:“HAL_SPI_Init”错误没有定义
- php - 如何在 Laravel 上使用 eloquent 执行多表选择
- flutter - 如何使用 charts_flutter 包向条形图中的各个条形添加点击功能
- python - 一起出现在篮子里的物品
- mongodb - 使用 mongoDB 聚合查找百分比
- android - 如何获取扩展文件的 URL?
- c - UDP 在 localhost 中丢失数据包,而 Wireshark 看到它们
- java - 使用 Gson/Jackson 和 Spring Boot 重新创建没有字段属性的 DTO 类,而不是让它为空
- unity3d - 未检测到 Agora Unity 演示场景网络摄像头
- java - 做java教程,收到错误信息