首页 > 解决方案 > Drupal 8 和 PostgreSQL:如何在 WHERE 子句中使用表达式的结果?

问题描述

你好呀!

我使用 Drupal 的查询接口构造了一个数据库查询。这样,我还成功地添加了一个生成条件值的表达式。该条件字段的内容是 ISO 格式的日期字符串。

我现在想在 WHERE 子句中使用该计算字段。在另一个使用 MySQL 的项目中,我只能在 where 子句中使用带有表达式结果的名称,但这似乎在 PostgreSQL 中不起作用。我总是得到“列不存在”-错误,无论我是否在表达式名称前加上数据库表别名。

(原始和缩短的)查询如下所示(仍包含值占位符):

SELECT
  base.nid AS nid,
  base.type AS type,
  date.field_date_value AS start,
  date.field_date_end_value AS "end",
  CASE WHEN COALESCE(LENGTH(date.field_date_end_value), 0) > 0 THEN date.field_date_end_value ELSE date.field_date_value END AS datefilter
FROM {node} base
LEFT JOIN {node__field_date} date ON base.type = date.bundle AND base.nid = date.entity_id AND base.vid = date.revision_id AND attr.langcode = date.langcode AND date.deleted = 0
WHERE (base.type = :db_condition_placeholder_0) AND (datefilter > :db_condition_placeholder_2)
ORDER BY field_date_value ASC NULLS FIRST

如前所述,如果我使用“date.datefilter”或仅使用“datefilter”应用过滤器,则没有任何区别。如果我不尝试在 WHERE 部分中使用该字段/表达式,结果列表中的结果就很好。那么,如何使用表达式的结果来过滤查询结果呢?

任何提示表示赞赏!提前致谢!

标签: postgresqldrupal-8drupal-database

解决方案


您可以尝试创建一个定义新列“datefilter”的派生表。

例如,而不是编码:

select case when c1 > 0 then c1 else -c1 end as c, c2, c3 
from t 
where c = 0;
ERROR:  column "c" does not exist
LINE 1: ...c1 > 0 then c1 else -c1 end as c, c2, c3 from t where c = 0;

定义一个派生表,该表定义新列并在外部 SELECT 中使用它:

select c, c2, c3 
from 
 (select case when c1 > 0 then c1 else -c1 end as c, c2, c3 from t) as t2 
where c=0;

推荐阅读