diff --git a/app/models/commit_status.rb b/app/models/commit_status.rb
index 535db26240a7985ce568c15d3238e78e1daac355..2d185c28809d69eced89d1057662c5c7d309d7e1 100644
--- a/app/models/commit_status.rb
+++ b/app/models/commit_status.rb
@@ -16,7 +16,11 @@ class CommitStatus < ActiveRecord::Base
 
   alias_attribute :author, :user
 
-  scope :latest, -> { where(id: unscope(:select).select('max(id)').group(:name, :commit_id)) }
+  scope :latest, -> do
+    max_id = unscope(:select).select("max(#{quoted_table_name}.id)")
+
+    where(id: max_id.group(:name, :commit_id))
+  end
   scope :retried, -> { where.not(id: latest) }
   scope :ordered, -> { order(:name) }
   scope :ignored, -> { where(allow_failure: true, status: [:failed, :canceled]) }
diff --git a/app/models/project.rb b/app/models/project.rb
index 80860f142d4c8775826a8ce50adb973d3a08f5d2..9f0dcb9a212f14d7fa6355a018cc3a5bcf314821 100644
--- a/app/models/project.rb
+++ b/app/models/project.rb
@@ -431,8 +431,13 @@ class Project < ActiveRecord::Base
 
   # ref can't be HEAD, can only be branch/tag name or SHA
   def latest_successful_builds_for(ref = default_branch)
-    pipeline = pipelines.latest_successful_for(ref)
-    builds.where(pipeline: pipeline).latest.with_artifacts
+    pipeline = pipelines.latest_successful_for(ref).to_sql
+    join_sql = "INNER JOIN (#{pipeline}) pipelines" +
+               " ON pipelines.id = #{Ci::Build.quoted_table_name}.commit_id"
+    builds.joins(join_sql).latest.with_artifacts
+    # TODO: Whenever we dropped support for MySQL, we could change to:
+    # pipeline = pipelines.latest_successful_for(ref)
+    # builds.where(pipeline: pipeline).latest.with_artifacts
   end
 
   def merge_base_commit(first_commit_id, second_commit_id)