0

I have two tables I need to select data from TABLE_A and TABLE_B; they have a one to many relationship.

In my select statement I will often get multiple unique results from TABLE_A and this is fine. But I will also get multiple matches in TABLE_B - I need to get the most recent TABLE_B record that matches. I have an auto incremented id tag that is available.

Here is a more detailed example:

TABLE_A

TABLE_A_id  data
-----------------------------
1           something    
2           somethignelse    
3           yetagainsomething

TABLE_B

TABLE_B_id  TABLE_A_id  data
------------------------------------
1           1           filler_data1
2           1           filler_data1
3           1           filler_data3
4           2           filler_data4
5           2           filler_data5
6           3           filler_data1

I need to select the data such that my returned array is something like this for a search on rows containing "filler_data1":

`TABLE_A_id` = 1, something, `TABLE_B_id` = 2, filler_data1

`TABLE_A_id` = 3, yetagainsomething, `TABLE_B_id` = 6, filler_data1

So in the above case I get the TABLE_B data which is the most recent, i.e. TABLE_B_id = 2 and matches the search of "filler_data1".

4

2 回答 2

1

This is the "greatest N per group query" question that comes up several times per week on StackOverflow.

SELECT A.*, B1.*
FROM TABLE_A A
JOIN TABLE_B B1 ON (A.A_ID = B1.A_ID)
LEFT OUTER JOIN TABLE_B B2 ON (A.A_ID = B2.A_ID AND B1.B_ID < B2.B_ID)
WHERE B2.B_ID IS NULL;
于 2009-09-16T00:21:51.913 回答
0

我过去采用的一种方法是创建一个包含最新信息的 table_b 视图,然后将 table_a 加入其中。举个例子。我们有一个事件跟踪系统。一个表包含与事件相关的所有常量数据,table_a。第二个表 table_b 充当审计表并跟踪事件的更新。我为每个特定事件创建了一个最近更新的视图,我将此视图用于各种报告,但我可以将此表连接到我的 table_a 以生成生成事件最新信息的结果。

于 2009-09-16T02:10:58.893 回答