我有这个表(比如TABLE1):
ID1 | ID2 | NAME
其中(ID1,ID2)是复合PK。
另一张桌子(比如TABLE2):
ID | COD1 | COD2 | DATA | INDEX
其中ID是PK。
我需要在((TABLE1.ID1 = TABLE2.COD1) AND (TABLE1.ID2 = TABLE2.COD2))
我的问题是,对于TABLE2的每个ID,我有许多具有不同INDEX的元组。我只想加入它的INDEX是其组中的MAX(COD1,COD2)的元组。
例如,如果我有:
ID1|ID2|NAME
10 10 JOSH
ID|COD1|COD2|DATA|INDEX
1 10 10 YES 0
2 10 10 NO 1
3 11 10 OH 0
我想得到:
ID1|ID2|NAME|DATA
10 10 JOSH NO
我试过这个,但它不起作用:
SELECT ID1, ID2, NAME, DATA
FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.ID1 = T2.COD1 AND T1.ID2 = T2.COD2
GROUP BY ID1, ID2, NAME, DATA HAVING INDEX = MAX(INDEX)
感谢。
答案 0 :(得分:2)
这是通用构造。
select field1,field2, etc
from yourtables
join
(select field1, max(something) themax
from table1
where whatever
group by field1) temp on table1.something = themax
and table1.field1 = temp.field1
where whatever
这两个"凡是哪个"应该是一样的。你应该可以从这里拿走它。
答案 1 :(得分:1)
略有不同的解决方案:
select t1.id1, t1.id2, t1."NAME", t3."DATA"
from table1 t1
left join
(
select max("INDEX") as maxindex, cod1, cod2
from table2
group by cod1, cod2
) tt on tt.cod1 = t1.id1 and tt.cod2 = t1.id2
left join table2 t2 on t2."INDEX" = tt.maxindex;
如果所有元组都有不同的唯一值INDEX,这些示例就可以了。但是,如果某些元组具有相同的值,则必须编写一个额外的子查询(例如,从table2中选择max(ID))以确定适当的行。
P.S。最好不要为自己的表或列使用任何关键字(例如INDEX,DATA ...)。
How To Handle Table Column Named With Reserved Sql Keyword?
Got an Oracle Table Named as Reserved Word, Which problems may arise?
答案 2 :(得分:0)
试
SELECT ID1,ID2,NAME
FROM TABLE1
join
(select ID,DATA, max(Index) themax
FROM TABLE2
WHERE (your condition)
group by ID) temp on table1.Index = themax
WHERE (your condition)
答案 3 :(得分:0)
我已经这样解决了:
SELECT ... FROM TABLE1 JOIN
(SELECT ID1, ID2, NAME, DATA
FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.ID1 = T2.COD1 AND T1.ID2 = T2.COD2
GROUP BY ID1, ID2, NAME, DATA HAVING INDEX = SELECT MAX(INDEX) FROM TABLE2 WHERE TABLE1.ID1 = TABLE2.COD1 AND TABLE1.ID2 = TABLE2.COD2
谢谢!