右表上有特殊条件的左连接
不知道这是否可能..我正在使用 sqlite3 架构:
CREATE TABLE 文档(id 整数主键,名称字符串);
CREATE TABLE revs(id整数主键,doc_id整数,number整数);
我想选择仅包含其中一个修订版(编号最高的修订版)的每一项作业。我怎样才能实现这个目标? 现在我正在做左连接并获取所有内容,然后我在应用程序中过滤它,但这很糟糕..
(顺便说一句,你能给我推荐一本关于数据库的好又简单的入门书以及如何它们可以工作,也许还有一些关于 sql 的东西..) 谢谢!
don't know if this is possible.. I'm using sqlite3
schema:
CREATE TABLE docs (id integer primary key, name string);
CREATE TABLE revs (id integer primary key, doc_id integer, number integer);
I want to select every job joined with only one of its revisions, the one with the highest number. How can I achieve this?
Right now I'm doing a left join and getting everything and then I'm filtering it in the application, but this sucks..
(by the way, can you suggest me a good and easy introductory book on databases and how they work and maybe something about sql too..)
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
试试这个
,或者,如果你想要没有修订的文档(这可能吗?)
try this
or, if you want the docs with no Revs (Is this possible?)
不确定您的引擎是否支持此功能,但通常,您会在 ANSI SQL 中执行类似的操作:
有多种方法可以编写等效查询,使用公用表表达式、相关聚合子查询等。
Not sure if your engine supports this, but typically, you would do something like this in ANSI SQL:
There are a number of ways to write equivalent queries, using common table expressions, correlated aggregate subqueries, etc.
数据库设计:为凡人设计数据库,作者:Hernandez
SQL:实用 SQL 手册
如果您想伤脑筋,可以阅读 乔·塞尔科。
Database Design : Database Design for Mere Mortals by Hernandez
SQL : The Practical SQL Handbook
If you want to hurt your head, any of the SQL books by Joe Celko.
这是一个非常好的数据库设计书籍列表
https://stackoverflow.com/search?q=database+book
Here is a very good list of books for Database Design
https://stackoverflow.com/search?q=database+book
如果每个作业都有修订(例如,从版本 0 开始),我将使用与 OrbMan 相同的方法,但使用内部联接。 (如果您确定正在寻找一对一的匹配。为什么不让 SQL 也知道呢?)
If every job has revisions (e.g., starting with rev 0), I would use the same approach as OrbMan, but with an inner join. (If you are certain you are looking for a 1-to-1 match. why not let SQL know, too?)
我推荐“数据库设计的合理方法”作为良好设计实践的优秀介绍。 (我有点偏见。我写的。但是,嘿,到目前为止,它在亚马逊上的平均评论为 5 星,这些评论都不是我或任何朋友或亲戚贡献的。)
I'd recommend "A Sane Approach to Database Design" as an excellent introduction to good design practices. (I am slightly biased. I wrote it. But hey, so far it has a 5-star average review on Amazon, none of which reviews were contributed by me or any friends or relatives.)