Koralek M.
Koralek M.

Reputation: 3341

Data from 2 tables

there are two tables:

TABLE cars

id | date
----------
1 | 2012-01-04
2 | 2012-01-04
3 | 2012-01-05

TABLE versions

id_car | year | author
-------------------------
1 | 2005 | John
1 | 2001 | Carl

2 | 2003 | Carl
2 | 2001 | John

3 | 2004 | Carl
3 | 2003 | John

I need to get all the information about cars with yesterday's date (2012-01-04) and information about their latest version if author is Carl.

So in this example I need to get: 2 | 2012-01-04 | 2003 | Carl

Upvotes: 1

Views: 54

Answers (1)

Eric
Eric

Reputation: 95103

You want an inner join:

select
    c.id,
    c.date,
    v.year,
    v.author
from
   cars c
   inner join versions v on
       c.id = v.id_car
   inner join (
        select 
            id_car, 
            max(year) as latestYear 
        from 
            versions 
        group by 
            id_car
    ) vmax on
       c.id = vmax.id_car
       and v.year = vmax.latestYear
where
   v.author = 'Carl'
   and c.date = '2012-01-04'

In this query, you're saying, "Grab me everything from cars where the date is 2012-01-04 and then find everything in versions where the id_car column is equal to my id column in cars. Oh, and only give me anything from versions where the author is Carl, but only where the year of the car is equal to the greatest year of the car that's available."

Upvotes: 5

Related Questions