假设数据库中有一个表comments
.
注释表有id
、text
、show
、comment_id_no
列.
如果用户输入注释,它会在数据库中插入一行
| id | comment_id_no | text | show | inserted_at |
| -- | -------------- | ---- | ---- | ----------- |
| 1 | 1 | hi | true | 1/1/2000 |
如果用户想要更新该注释,它会在数据库中插入一个新行
| id | comment_id_no | text | show | inserted_at |
| -- | -------------- | ---- | ---- | ----------- |
| 1 | 1 | hi | true | 1/1/2000 |
| 2 | 1 | hey | true | 1/1/2001 |
注意它保持不变的comment_id_no
.这样我们就能看到 comments 的历史了.
现在用户决定不再显示他们的 comments
| id | comment_id_no | text | show | inserted_at |
| -- | -------------- | ---- | ----- | ----------- |
| 1 | 1 | hi | true | 1/1/2000 |
| 2 | 1 | hey | true | 1/1/2001 |
| 3 | 1 | hey | false | 1/1/2002 |
这会对最终用户隐藏 comments .
现在发表第二条 comments (不是第一条的更新)
| id | comment_id_no | text | show | inserted_at |
| -- | -------------- | ---- | ----- | ----------- |
| 1 | 1 | hi | true | 1/1/2000 |
| 2 | 1 | hey | true | 1/1/2001 |
| 3 | 1 | hey | false | 1/1/2002 |
| 4 | 2 | new | true | 1/1/2003 |
我希望能够 Select unique commend_id_no
的所有最新版本,其中show
等于true.但是,我不希望查询返回id=2
.
查询需要采取的步骤...
- Select 所有最近的、不同的
comment_id_no
个.(应返回id=3
和id=4
) - Select show=true的位置(应仅返回
id=4
)
注意:我实际上是在用elixir编写这个查询,使用的是ecto,我希望不使用子查询函数也能做到这一点.如果有人能用sql回答这个问题,我可以自己转换答案.如果有人知道如何用长生不老药来回答这个问题,那么也可以随意回答.