【问题标题】:Drupal 8 and PostgreSQL: How can I use the result of an expression inside a WHERE clause?Drupal 8 和 PostgreSQL:如何在 WHERE 子句中使用表达式的结果?
【发布时间】:2020-06-27 08:04:52
【问题描述】:

你好!

我使用 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 部分中使用该字段/表达式,结果列表中的结果就很好。那么,如何使用表达式的结果来过滤查询结果呢?

感谢任何提示!提前致谢!

【问题讨论】:

    标签: postgresql drupal-8 drupal-database


    【解决方案1】:

    您可以尝试创建一个定义新列“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;
    

    【讨论】:

    • 不幸的是,这在 AFAIK 中是不可能的,因为我没有直接编写 SQL,而是使用 Drupal 的数据库查询接口......
    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2011-09-26
    相关资源
    最近更新 更多