【问题标题】:Error in migration - Error: You have an error in your SQL syntax; check the manual that corresponds迁移错误 - 错误:您的 SQL 语法有错误;检查相应的手册
【发布时间】:2015-07-10 14:47:00
【问题描述】:

无法理解语法 sql 文件迁移有什么问题。请帮忙:

我运行 rake db:migrate

错误:

Mysql2::Error: 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 ')' 附近使用正确的语法: UPDATE photos SET votes_count = 0, rating = 0 WHERE id NOT IN ()/home/user/myapp/appmame/db /migrate/20131110162613_recalculate_photos_rating.rb:8:in `up'

class RecalculatePhotosRating < ActiveRecord::Migration
  def up
    if Vote.where("subject_type='Photo' and rating > 1").count > 0
      ActiveRecord::Base.connection.execute "DELETE FROM votes WHERE subject_type='Photo' AND rating <= 5"
      ActiveRecord::Base.connection.execute "UPDATE votes SET rating=1 WHERE subject_type='Photo'"
    end
    pids = Vote.where(subject_type: 'Photo').pluck(:subject_id).uniq
    ActiveRecord::Base.connection.execute "UPDATE photos SET votes_count = 0, rating = 0 WHERE id NOT IN (#{pids.join(', ')})"
    ActiveRecord::Base.connection.execute "UPDATE photos SET rating=(SELECT COUNT(*) FROM votes WHERE votes.subject_type='Photo' AND subject_id=photos.id) WHERE id IN (#{pids.join(', ')})"
    ActiveRecord::Base.connection.execute "UPDATE photos SET votes_count=(SELECT COUNT(*) FROM votes WHERE votes.subject_type='Photo' AND subject_id=photos.id) WHERE id IN (#{pids.join(', ')})"
  end

  def down
  end
end

【问题讨论】:

    标签: mysql ruby-on-rails mysql2


    【解决方案1】:

    您必须检查pids 查询是否返回空结果:

    class RecalculatePhotosRating < ActiveRecord::Migration
      def up
        if Vote.where("subject_type='Photo' and rating > 1").count > 0
          ActiveRecord::Base.connection.execute "DELETE FROM votes WHERE subject_type='Photo' AND rating <= 5"
          ActiveRecord::Base.connection.execute "UPDATE votes SET rating=1 WHERE subject_type='Photo'"
        end
        pids = Vote.where(subject_type: 'Photo').pluck(:subject_id).uniq
        unless pids.empty?
          ActiveRecord::Base.connection.execute "UPDATE photos SET votes_count = 0, rating = 0 WHERE id NOT IN (#{pids.join(', ')})"
          ActiveRecord::Base.connection.execute "UPDATE photos SET rating=(SELECT COUNT(*) FROM votes WHERE votes.subject_type='Photo' AND subject_id=photos.id) WHERE id IN (#{pids.join(', ')})"
          ActiveRecord::Base.connection.execute "UPDATE photos SET votes_count=(SELECT COUNT(*) FROM votes WHERE votes.subject_type='Photo' AND subject_id=photos.id) WHERE id IN (#{pids.join(', ')})"
        end
      end
    
      def down
      end
    end
    

    【讨论】:

    • 我插入了除非 pids.empty?又是同样的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多