mysql - 子查询返回多于 1 行的 sql 查询

标签 mysql sql

我有这样的错误可以解释我做错了什么吗?
我只添加这个 sql 查询:

 (? = (select travel_region_id from relationships where travel_id = travels.id))

错误

ActiveRecord::StatementInvalid (Mysql::Error: Subquery returns more than 1 row: select count(*) from travel_start_days, cars, travels
                   where travels.id = travel_start_days.travel_id and travels.id = travel.car_id and travel_start_days.day > adddate(curdate(), interval '2' day) and (7 = (select travel_region_id from relationships where travel_id = travels.id)) and '2013-08-16' <= travel_start_days.day):

更新 Whis方法创建查询

def conditions
      where = ''
      param = []
      if @region && @region != ''
        where += 'travels.region_id = ?'
        param += [@region.to_i]
      end
      if @car && @car != ''
        where += ' and ' if where != ''
        where += 'cars.id = ?'
        param += [@car.to_i]
      end
      if @relation && @relation != '' 
        where += ' and ' if where != ''
        where += '(? = (select travel_region_id from relationships where travel_id = travels.id))'
        param += [@relation.to_i]
      end
      if @start_port && @start_port != ''
        where += ' and ' if where != ''
        where += '(? = (select location_id from travel_days where travel_id = travel_start_days.travel_id and day_no = 1 order by arrival asc limit 1))'
        param += [@start_port.to_i]
      end
      return where == '' ? nil : ["travel_start_days.day > adddate(curdate(), interval ? day) and " + where] + [@criteria[5]] + param
    end

最佳答案

这部分条件的问题:

(7 = (select travel_region_id from relationships where travel_id = travels.id)) 

显然这个子查询返回了多个 travel_region_id 只需将 = 替换为 IN

(7 IN (select travel_region_id from relationships where travel_id = travels.id)) 

关于mysql - 子查询返回多于 1 行的 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18268182/

相关文章:

如果内联指定密码,mysql 无法连接到数据库

python - Pyspark DataFrame 中的嵌套 SELECT 查询

sql - 来自嵌套连接的单行

mysql - 如何查明子表中的所有 FK 引用是否都存在于父表中

php - 带参数的 Doctrine2 DQL TRIM

MySQL 查询运行很长时间将日期时间转换为日期

Python pymssql : Adaptive Server connection failed

sql - 选择其他列值以及 min(salary),其中可能存在重复的工资

php - 使用谷歌云存储/bigdata作为php应用程序的mysql数据库

MySQL 根据日期从多个表中获取结果