我有以下查询
SELECT product.*,
(SELECT bid FROM server1 WHERE product_id = product.id) AS bid1,
(SELECT bid FROM server2 WHERE product_id = product.id) AS bid2,
CASE
WHEN bid1 > bid2 THEN '1 wins'
WHEN bid2 > bid1 THEN '2 wins'
ELSE 'undecided'
END AS bid_status
FROM product
WHERE id= $1
此查询在CASE语句中引发错误,指出bid1
列不存在。如何将子查询作为case语句的变量传递?
答案 0 :(得分:2)
范围问题。首先将查询包装为派生表:
select dt.*
CASE
WHEN bid1 > bid2 THEN '1 wins'
WHEN bid2 > bid1 THEN '2 wins'
ELSE 'undecided'
END AS bid_status
from
(
SELECT product.*,
(SELECT bid FROM server1 WHERE product_id = product.id) AS bid1,
(SELECT bid FROM server2 WHERE product_id = product.id) AS bid2,
FROM product
WHERE id= $1
) dt