我刚刚将我的网站上传到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'"
答案 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
级别声明的列。