将sqlite3查询转换为postgres

时间:2017-07-18 15:25:24

标签: ruby-on-rails postgresql heroku sqlite

我刚刚将我的网站上传到Heroku但是我的一个控制器出错了。显然我的postgres代码有语法错误。这适用于sqlite3但是当我将其转换为postgres时发生了语法错误。

   @cars=Car.find_by_sql("SELECT cars.*, CASE WHEN EXISTS (SELECT book_cars.* FROM book_cars WHERE book_cars.car_id=cars.id AND book='t') THEN 'TRUE' ELSE 'FALSE' END  AS 'is_book' FROM cars WHERE is_book='FALSE'")

有关导致错误的原因的任何想法?  错误代码:

PG::SyntaxError: ERROR:  syntax error at or near "'is_book'"

1 个答案:

答案 0 :(得分:1)

尝试简单:

SELECT *, 'FALSE' As is_book
FROM cars c
WHERE NOT EXISTS (
   SELECT * FROM book_cars b
   WHERE b.car_id=c.id AND book = 't'
)

您也可以使用子查询:

SELECT *
FROM (
   SELECT cars.*, 
          CASE WHEN EXISTS (
              SELECT book_cars.* FROM book_cars 
              WHERE book_cars.car_id=cars.id AND book='t') 
          THEN 'TRUE' ELSE 'FALSE' END  AS is_book
   FROM cars 
) x
WHERE is_book='FALSE';

修改

您的查询中的问题位于以下最后一行的WHERE子句中:

SELECT cars.*, 
       CASE WHEN EXISTS (
            SELECT book_cars.* FROM book_cars 
            WHERE book_cars.car_id=cars.id AND book='t') 
       THEN 'TRUE' ELSE 'FALSE' END  AS 'is_book' 
FROM cars 
WHERE is_book='FALSE';

在标准SQL WHERE子句中,没有看到SELECT子句中声明的任何表达式(或"列"),它只能看到表中的列FROM条款 is_book子句中声明了SELECT列,因此WHERE无法看到它 如果使用子查询,例如:

SELECT *
FROM ( --- subquery
   SELECT some_expression AS new_column
   FROM ....
) x
WHERE new_column = 111

然后外部查询会看到新列。

您也可以使用HAVING子句:

SELECT cars.*, 
       CASE WHEN EXISTS (
            SELECT book_cars.* FROM book_cars 
            WHERE book_cars.car_id=cars.id AND book='t') 
       THEN 'TRUE' ELSE 'FALSE' END  AS 'is_book' 
FROM cars 
HAVING is_book='FALSE';

因为与HAVING相比,WHERE确实会看到在SELECT级别声明的列。