SQL右连接,强制从右侧仅返回一个值
table 1
---
id , name
table2
---
id , activity, datefield
table1 'right join' table2 将从右表 (table2) 返回 1 个以上结果。如何让它从具有最高日期的 table2 中仅返回“1”结果
table 1
---
id , name
table2
---
id , activity, datefield
table1 'right join' table2 will return more than 1 results from right table (table2) . how to make it return only "1" result from table2 with the highest date
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你写的关于你的问题的信息很差,但我会尝试举一个例子来帮助你。
您有一个表“A”和一个表“B”,并且需要获取与表“A”相关的表“B”的“顶部”日期
示例表:< /em>
如果执行此 sql:
您将获得通过 ID 关联的 A 和 B 的所有信息(在这种理论情况下,这是两个表链接关系的公共字段)
但是您只需要表 A 中每个元素的最后一个日期(B 的顶部日期)
接下来,如果您只需要获取顶部日期,您需要按 B.AID 对查询进行分组,并仅获取顶部日期
此操作的结果是:
在这个结果中,我删除了一些重复的字段(例如 A.AID 和 B.AID,这是两个表之间的关系)或不需要的字段。
You write poor information about your problem, But I'll try to make an example to help you.
You have a table "A" and a table "B" and you need to fetch the "top" date of table "B" that is related with table "A"
Example tables:
If you do this sql:
You get all information of A and B that is related by ID (that in this theoretical case is the field that is common for both tables to link the relation)
But you require only the last date for each element of the Table A (the top date of B)
Next if you need to get only the top DATE you need to group your query by the B.AID and fetch only the top date
And The result of this operation is:
In this result I removed some fields that are duplicated (like A.AID and B.AID that is the relationship between the two tables) or are not required.
在 table1.id 上右连接 table2 以从 table2 中选择 id, max = max(date)
right join table2 on on table1.id to to select id, max = max(date) from table2
分析!
测试数据:
查询:
外部 where 子句将过滤掉 t2 元组中除最大日期之外的所有内容,但保留 t2 中没有匹配行的空行。
结果:
Analytics!
Test data:
Query:
The outer where clause will filter out all but the maximum date from t2 tuples, but leave in the null row where there was no matching row in t2.
Results:
要从查询中检索前 N 条记录,可以使用以下语法:
PS:我不熟悉 PL/SQL,所以也许我错了
To retrieve the Top N records from a query, you can use the following syntax:
PS: I am not familiar with PL/SQL so maybe I'm wrong
我的解决方案是
select from table1 right join table2 on (table1.id= table2.id and table2.datefiled= (select max(datefield) from table2 where table2.id= table1.id) )
my solution is
select from table1 right join table2 on (table1.id= table2.id and table2.datefiled= (select max(datefield) from table2 where table2.id= table1.id) )