# Fetching data from two or more tables

**URL:** <https://www.ruby-forum.com/t/fetching-data-from-two-or-more-tables/160434>\
**Category:** Deployment\
**Created:** [February 16, 2009, 12:15pm UTC](https://www.ruby-forum.com/t/fetching-data-from-two-or-more-tables/160434 "2009-02-16T12:15:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tnyplz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/f17d59/32.png) [@tnyplz](https://www.ruby-forum.com/u/tnyplz)\
**Post date:** [February 16, 2009, 12:15pm UTC](https://www.ruby-forum.com/t/fetching-data-from-two-or-more-tables/160434/1 "2009-02-16T12:15:19Z")

</div>

Hi all,

Say, I have two tables (requirements & projreqs)and want to execute the  
following query.  
SELECT \* FROM requirements WHERE(id = (SELECT req\_id FROM projreqs WHERE  
proj\_id = ?));

Being a newbie in Ruby, I know only to extract data from one table.  
Eg: Requirement.find(:all, :select, :condition) or  
Requirement.find\_by\_sql(query).

But, how to combine two tables? Please help me out…

Appreciate your help.

Thanks,  
Tony P.

---

<div class="post-metadata">

**Author:** ![tnyplz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/f17d59/32.png) [@tnyplz](https://www.ruby-forum.com/u/tnyplz)\
**Post date:** [November 7, 2009, 7:34am UTC](https://www.ruby-forum.com/t/fetching-data-from-two-or-more-tables/160434/2 "2009-11-07T07:34:09Z")

</div>

Tony P. wrote:

> Hi all,
> 
> Say, I have two tables (requirements & projreqs)and want to execute the  
> following query.  
> SELECT \* FROM requirements WHERE(id = (SELECT req\_id FROM projreqs WHERE  
> proj\_id = ?));
> 
> Being a newbie in Ruby, I know only to extract data from one table.  
> Eg: Requirement.find(:all, :select, :condition) or  
> Requirement.find\_by\_sql(query).
> 
> But, how to combine two tables? Please help me out…
> 
> Appreciate your help.
> 
> Thanks,  
> Tony P.

Hi,  
Extract data from two table or more table it’s required that there  
is some relation exist between them. As per your need you use join or  
include for that.

For more information go through this url

> **[ActiveRecord::Associations::ClassMethods](https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html)**
>
> Associations are a set of macro-like class methods for tying objects together through foreign keys.

Thanks,  
Priyanka P.
