Friday, November 27, 2009

Using Joins with MySQL Queries and Convert to RoR

Using Joins on MySQL queries and then convert to RoR.

1) Self Join with Rails.

Table Name - "Comment",
Attributes - "Id,Comment_Detail,Parent_Id"

Sample Comment Data
----------------------------------------------------------

|| Id || Comment_Detail || Parent_Id
-----------------------------------------------------------
|| 1 || Krunal || nil

|| 2 || Nishant || 1

|| 3 || Nirali || nil

|| 4 || Manan || 3

|| 5 || Ankit || nil

----------------------------------------------------------------
  • Query :-> To fetch only parent comments which has nil parent_id and also want count of their child comments.
MySql Syntax :->

(SELECT b.*,(select count(*) from comments c where c.parent_id = b.id ) as commentcount FROM `comments` b WHERE (parent_id is NULL) ORDER BY created_at DESC LIMIT 5)

Conversion to Rails Syntax :->

Comment.find(:all,:select => "b.*, (select count(*) from comments c where c.parent_id = b.id) as count", :conditions => ["parent_id is NULL)"], :from => "comments as b",:order => "b.created_at DESC",:limit => 5)


2) Another Query

Table Name "Video", Attributes "Id,title,created_at,updated_at"
Table Name "Views", Attributes "Id,Viewable_type,Viewable_id"

  • Relation :-> One video has many views.
  • Query :-> To fetch videos with it's view count.

MySql Syntax :->

(select a.*,(select count(*) from views where viewable_type = 'video' and viewable_id = a.id ) as videosviews from videos a order by videosviews DESC LIMIT 15)

Conversion to Rails Syntax :->

Video.find(:all,:select => "a.*,(select count(*) from views where viewable_type = 'video' and viewable_id = a.id ) as viewscount",:order => "viewscount DESC", :limit => 15,:from => "videos as a")