嘗試簡單:
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
級別定義的字段。
嘗試將''is_book''更改爲'is_book'(不含''')。 –
我試着這樣做,然後錯誤成爲:PG :: UndefinedColumn:錯誤:列「is_book」不存在 – Acrux
你確定'is_book'列確實存在嗎? –