在 Postgresql 的 where 子句中使用 Alias 列
我有一个这样的查询:
SELECT
jobs.*,
(
CASE
WHEN lead_informations.state IS NOT NULL THEN lead_informations.state
ELSE 'NEW'
END
) AS lead_state
FROM
jobs
LEFT JOIN lead_informations ON
lead_informations.job_id = jobs.id
AND
lead_informations.mechanic_id = 3
WHERE
lead_state = 'NEW'
给出以下错误:
PGError: ERROR: column "lead_state" does not exist
LINE 1: ...s.id AND lead_informations.mechanic_id = 3 WHERE (lead_state...
在 MySql 中这是有效的,但显然在 Postgresql 中不是。据我所知,原因是查询的 SELECT 部分的计算晚于 WHERE 部分。这个问题有通用的解决方法吗?
I have a query like this:
SELECT
jobs.*,
(
CASE
WHEN lead_informations.state IS NOT NULL THEN lead_informations.state
ELSE 'NEW'
END
) AS lead_state
FROM
jobs
LEFT JOIN lead_informations ON
lead_informations.job_id = jobs.id
AND
lead_informations.mechanic_id = 3
WHERE
lead_state = 'NEW'
Which gives the following error:
PGError: ERROR: column "lead_state" does not exist
LINE 1: ...s.id AND lead_informations.mechanic_id = 3 WHERE (lead_state...
In MySql this is valid, but apparently not in Postgresql. From what I can gather, the reason is that the SELECT
part of the query is evaluated later than the WHERE
part. Is there a common workaround for this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我在同样的问题上苦苦挣扎,“mysql语法是非标准的”在我看来不是一个有效的论点。 PostgreSQL 还添加了方便的非标准扩展,例如“INSERT ... RETURNING ...”以在插入后获取自动 ID。此外,重复大型查询并不是一个优雅的解决方案。
但是,我发现 WITH 语句 非常有帮助(CTE)。它在查询中创建一个临时视图,您可以像普通表一样使用它。我不确定我是否正确重写了您的 JOIN,但一般来说它应该像这样工作:
I struggled on the same issue and "mysql syntax is non-standard" is not a valid argument in my opinion. PostgreSQL adds handy non-standard extensions as well, for example "INSERT ... RETURNING ..." to get auto ids after inserts. Also, repeating large queries is not an elegant solution.
However, I found the WITH statement very helpful (CTE's). It sort of creates a temporary view within the query which you can use like a usual table then. I'm not sure if I have rewritten your JOIN correctly, but in general it should work like this:
您需要在 where 子句中复制 case 语句,或者我更喜欢执行如下操作:
You would need to either duplicate the case statement in the where clause, or my preference is to do something like the following:
正如您所经历的,MySQL 的支持是非标准的。正确的方法是重新打印 SELECT 子句中使用的相同表达式:
MySQL's support is, as you experienced, non-standard. The correct way is to reprint the same expression used in the SELECT clause:
我认为常见的解决方案是使用内部 SELECT 进行计算(在本例中为 CASE 语句),以便在执行到该查询时,内部 SELECT 的结果可用于整个外部查询。否则,首先计算 WHERE 子句,并且对 SELECT 子句一无所知。
I believe the common solution is to use an inner SELECT for the calculation (or CASE statement in this case) so that the result of the inner SELECT is available to the entire outer query by the time the execution gets to that query. Otherwise, the WHERE clause is evaluated first and knows nothing about the SELECT clause.
子查询:
Subquery:
我在这样的地方使用了别名。 (子查询)。
I used alias in where like this. (Sub Query).