postgresql - 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 部分中使用该字段/表达式,结果列表中的结果就很好。那么,如何使用表达式的结果来过滤查询结果呢?
任何提示表示赞赏!提前致谢!
解决方案
您可以尝试创建一个定义新列“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;
推荐阅读
- google-chrome - 运行带有扩展的 vscode chrome 调试器
- javascript - 如何在 uglifyJsPlugin 中恢复控制台警报
- javascript - 使用书签启动 WebPageTest.org 的测试
- django - 不断地从服务器向客户端发送数据
- node.js - nodejs lambda发布请求超时
- magento2 - Magento 2 - 在 Braintree 信用卡表格中添加自动填充
- java - 删除工具栏中 ImageView 和后退箭头之间的空间
- java - Spring应用程序基本身份验证通过keycloack
- java - 异步加载 JButton 图标
- java - 无法使用 Java/Kotlin 加密/解密字符串