Les_Salantes
Les_Salantes

Reputation: 315

Joining 3 tables pgsql

I have 3 tables as shown below

table 1
________________________________________________
id | effective_date     | table_3_id | acc_name |
___|____________________|____________|__________|
112|2012-02-01 12:00:00 |     23     | Over Pay |
___|____________________|____________|__________|

table 2
__________________________________
id    | table_1_id     | amount  |
______|________________|_________|
 1    |    112         |  400.00 |
______|________________|_________|

table 3
________________________________________
id  | emp_num  | first_name  | last_name|
____|__________|_____________|__________|
 23 |   100004 |   John      |    Doe   |  
____|__________|_____________|__________|

I have a start date and an end date and also a predefined value for acc_name. What I want to do is, to retrieve the emp_num, first_name, last_name and amount from relevant tables that have a effective_date that falls between start date and end date and also the acc_name should be the predefined value.

For above tables if my start date = 2012-01-30 12:00:00 , end date = 2012-03-01 12:00:00 and acc_name = Over Pay; then below values should be returned.

emp_num = 100004  
first_name = John  
last_name = Doe  
amount = 400.00

How can I do this? I am not sure whether joining all 3 the tables is the best approach here. Can anyone help?

Upvotes: 2

Views: 5170

Answers (2)

John Woo
John Woo

Reputation: 263683

Here, try this one:

SELECT  a.emp_num,
        a.first_name,
        a.last_name,
        c.amount
FROM    table3 a
            INNER JOIN table1 b
                on a.id = b.table_3_id
            INNER JOIN table2 c
                on b.id = c.id
WHERE   b.effective_date BETWEEN '2012-01-30 12:00:00' AND '2012-02-29 12:00:00' 
        AND
        b.acc_name = 'Over pay'

Upvotes: 0

podiluska
podiluska

Reputation: 51494

Yes. Use a join.

select emp_num, first_name, last_name, amount
from 
    table1 
       inner join table2 on table1.id = table2.table_1_id
       inner join table3 on table1.table_3_id = table3.id
where
    effective_date between '2012-01-30 12:00:00' and '2012-03-01 12:00'
and 
    acc_name = 'Over Pay'

There is no 30th of February.

Upvotes: 2

Related Questions