Sri
Sri

Reputation: 121

How to get Data form a table based on the foreign key in sql

Table 1

enter image description here

Table 2

enter image description here

Here wish to get the data from Table 1 which is created between 5\09\2018 to 26\12\2018. Here PostID is the foreign key.

Thanks in advance

Upvotes: 0

Views: 661

Answers (3)

Will Kong
Will Kong

Reputation: 71

If you just query data from Table 1, you may write the query like this.

select 
* 
from table1 T
where T.DateCreated between '2018-09-05 00:00:00' and '2018-12-26 23:59:59'
and exists (select 1 from table2 where PostID=T.PostID)

Best Regards,

Will

Upvotes: 1

Vinit Raj
Vinit Raj

Reputation: 11

Select * from table1 t1 inner join table2 t2 on t1.PostID=t2.PostID where t2.PostID=1

For inner join foreign key is mandatory, and the reference column will come in the join condition.

Upvotes: 1

Ajan Balakumaran
Ajan Balakumaran

Reputation: 1649

You can join both tables and use where statement to retrieve the relevant data,

Select * 
from table1 t1
inner join table2 t2
on t1.PostID=t2.PostID
where t1.datecreated between '2018-09-05' and  '2018-12-26'

Upvotes: 1

Related Questions