I have two tables :
T_STOCK
: primary key is id
, seller
, and some others fields let say a
and b
.
T_FLOW
: primary key is (id
+ startdate
), and some others fields, for example c
and d
.
I want a query that returns all the columns for each records from T_STOCK
regarding a specific seller
, but completed with the columns (startDate
, c
and d
) from the T_FLOW
table.
The relation between T_STOCK
and T_FLOW
is based on the id
attribute.
Everytime a record with a specific ID exists in T_STOCK
, at least one record exist in T_FLOW
for this ID.
However, it may happen that more than one record exist in T_FLOW
. In this case, I must consider only the most recent one (i.e. the one with max(startDate)
).
In others words, if we have the following tables content:
+---------------------+
| T_STOCK |
+----+--------+---+---+
| ID | SELLER | a | b |
+----+--------+---+---+
| 01 | foobar | 1 | 2 |
+----+--------+---+---+
| 02 | foobar | 3 | 4 |
+----+--------+---+---+
| 03 | foobar | 5 | 6 |
+----+--------+---+---+
+---------------------------+
| T_FLOW |
+----+------------+----+----+
| ID | StartDate | c | d |
+----+------------+----+----+
| 01 | 01/01/2010 | 7 | 8 |
+----+------------+----+----+
| 02 | 01/01/2010 | 9 | 10 |
+----+------------+----+----+
| 02 | 07/01/2010 | 11 | 12 |
+----+------------+----+----+
| 03 | 03/01/2010 | 13 | 14 |
+----+------------+----+----+
| 03 | 05/01/2010 | 15 | 16 |
+----+------------+----+----+
The result of the query must be :
+----+--------+---+---+------------+----+----+
| ID | SELLER | a | b | startDate | c | d |
+----+--------+---+---+------------+----+----+
| 01 | foobar | 1 | 2 | 01/01/2010 | 7 | 8 |
+----+--------+---+---+------------+----+----+
| 02 | foobar | 3 | 4 | 03/01/2010 | 11 | 12 |
+----+--------+---+---+------------+----+----+
| 03 | foobar | 5 | 6 | 01/01/2010 | 15 | 16 |
+----+--------+---+---+------------+----+----+
How do I write my query then?