2010-08-13 41 views
1
table 1 
--- 
id , name 

table2 
--- 
id , activity, datefield 

表1'右连接'表2将从右表(表2)返回多于1个结果。如何使它从表2最高日仅返回“1”的结果SQL右连接,仅从右侧返回一个值

+0

需要更多的上下文:你只是有兴趣在每某些标准的最大日期表2的形式,或者从表2一堆列? – 2010-08-13 08:45:45

+0

table1连接table2,table3,table4..etc ..我想从table2得到一行,但后来整个查询,我想返回一堆列 – cometta 2010-08-13 08:55:57

回答

2

右连接表2上table1.id来选择ID,最大值=最大值从表2

(日期)
+0

我的表1连接到tabl2旁边的许多其他表,所以我不能像你一样使用查询,因为这会返回1个结果。看到我更新的问题。我想table2只返回最新的“datefield” – cometta 2010-08-13 08:48:40

0

要检索前N个从查询的记录,你可以使用下面的语法:

SELECT * 
FROM (your ordered by datefield desc query with join) alias_name 
WHERE rownum <= 1 
ORDER BY rownum; 

PS:我不熟悉PL/SQL,所以也许我错了

+0

nope,那不是我想要的。如我所说,我仍然希望返回超过1个结果,我还与table2旁边的许多其他表一起加入。但是当'正确加入table2'时,这部分我想返回1记录与最大日期 – cometta 2010-08-13 08:54:39

3

你写你的问题的信息不畅,但我我会试着做一个例子来帮助你。

你有一个表“A”和一张桌子“B”,你需要获取一个与台“A”

例表相关表“B”的“顶部”日期:

Table A: 
AID| NAME 
----|----- 
    1 | Foo 
    2 | Bar 

Table B: 

BID | AID | DateField 
----| ----| ---- 
1 | 1 | 2000-01-01 
2 | 1 | 2000-01-02 
3 | 2 | 2000-01-01 

如果你这样做SQL:

SELECT * FROM A RIGHT JOIN B ON B.ID = A.ID 

你得到由ID相关的A和B的所有信息(即在这一理论的情况是很常见的两个表的联系纽带场)

A.AID | A.NAME | B.BID | B.AID | B.DateField 
------|--------|-------|-------|-------------- 
    1 | Foo | 1 | 1 | 2000-01-01 
    1 | Foo | 2 | 1 | 2000-01-02 
    2 | Bar | 3 | 2 | 2000-01-01 

但是你只需要为每个的最后日期在表A的元素(B的顶部日期)

接下来,如果你需要得到只有顶部日期你在B.AID需要组查询并只获取顶部日期

SELECT 
     B.AID, First(A.NAME), MAX(B.DateField) 
FROM 
     A RIGHT JOIN B ON B.ID = A.ID 
GROUP BY 
     B.AID 

而这个操作的结果是:

B.AID | A.NAME | B.DateField 
------|--------|-------------- 
    1 | Foo | 2000-01-02 
    2 | Bar | 2000-01-01 

在该结果我删除被复制(如A.AID和B.AID即两个表之间的关系)或不需要某些字段。

  • 提示:如果你有更多的表到SQL中,这也适用。 sql“查询”并接着应用一个分组来使用B来限制B到顶部日期的重复。
0

我的解决办法是

选择从表1右连接表2对(table1.id = table2.id和table2.datefiled =(请从表2 MAX(的DateField),其中table2.id = table1.id) )

1

Analytics(分析)!

测试数据:

create table t1 
    (id  number  primary key, 
    name  varchar2(20) not null 
); 

create table t2 
    (id  number not null, 
    activity varchar2(20) not null, 
    datefield date not null 
); 

insert into t1 values (1, 'foo'); 
insert into t1 values (2, 'bar'); 
insert into t1 values (3, 'baz'); 

insert into t2 values (1, 'foo activity 1', date '2009-01-01'); 
insert into t2 values (2, 'bar activity 1', date '2009-01-01'); 
insert into t2 values (2, 'bar activity 2', date '2010-01-01'); 

查询:

select id, name, activity, datefield 
    from (select t1.id, t1.name, t2.id as t2_id, t2.activity, t2.datefield, 
       max(datefield) over (partition by t1.id) as max_datefield 
      from t1 
       left join t2 
       on t1.id = t2.id 
     ) 
where ((t2_id is null) or (datefield = maxdatefield)) 

外where子句会过滤掉所有,但由T2元组的最大日期,但空行那里是不留在t2中匹配行。

结果:

 ID NAME    ACTIVITY     DATEFIELD 
---------- -------- -------------------  ------------------- 
     1 foo   foo activity 1  2009-01-01 00:00:00 
     2 bar   bar activity 2  2010-01-01 00:00:00 
     3 baz