【问题标题】:use alias name as parameter使用别名作为参数
【发布时间】:2021-05-28 09:31:13
【问题描述】:

如何获取查询的别名。下面我使用带有hibernate JPA本机查询的spring boot。我想要的是获取别名 cbpartnerid 作为 WHERE 参数,因为我从有条件的 2 个表中获取 c_b_partner

但是春天给了我这个错误:

错误 2021-02-26 06:00:02.492 [http-nio-8080-exec-9] o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions(142) - 错误:“cbpartnerid”列不存在

我希望可以在不改变整体查询或修改后端代码的情况下解决这个问题。

这是我的本地查询:

(CASE
WHEN i.transaction = 'SALES' OR i.transaction = 'CUSTOMER_RETURN' THEN j.c_bpartner_id
WHEN i.transaction = 'INVENTORY_OUT' OR i.transaction = 'INVENTORY_OUT' THEN l.c_bpartner_id
ELSE null
END) AS **cbpartnerid**
FROM so_transaction i
LEFT JOIN so_orderline j ON j.so_orderline_id = i.so_orderline_id LEFT JOIN so_inventoryline k ON k.so_inventoryline_id = i.so_inventoryline_id
LEFT JOIN so_inventory l ON  l.so_inventory_id = k.so_inventory_id
GROUP BY i.created, i.transaction, i.m_product_id, i.productname, i.createdby, **cbpartnerid** ORDER BY i.m_product_id DESC ```

【问题讨论】:

    标签: postgresql spring-boot hibernate


    【解决方案1】:
    SELECT i.created, i.transaction, i.m_product_id, i.productname, i.createdby,
    (CASE
    WHEN i.transaction = 'SALES' OR i.transaction = 'CUSTOMER_RETURN' THEN j.c_bpartner_id
    WHEN i.transaction = 'INVENTORY_OUT' OR i.transaction = 'INVENTORY_OUT' THEN l.c_bpartner_id
    ELSE null
    END) AS **cbpartnerid**
    FROM so_transaction i
    LEFT JOIN so_orderline j ON j.so_orderline_id = i.so_orderline_id LEFT JOIN so_inventoryline k ON k.so_inventoryline_id = i.so_inventoryline_id
    LEFT JOIN so_inventory l ON  l.so_inventory_id = k.so_inventory_id
    GROUP BY i.created, i.transaction, i.m_product_id, i.productname, i.createdby, **cbpartnerid** ORDER BY i.m_product_id DESC ```
    

    【讨论】:

      【解决方案2】:

      简单的解决方案是子查询。

      你的代码,简化为基本的,看起来像

      SELECT /* complicated expression */ AS alias,
             /* other columns */
      FROM atable
      GROUP BY alias;
      

      这可以重写为

      SELECT alias, /* other columns */
      FROM (SELECT /* complicated expression */ AS alias,
                   /* other columns */
            FROM atable) AS subq
      GROUP BY alias;
      

      【讨论】:

      • 感谢@laurenz-albe 的回答。我会尽快检查
      猜你喜欢
      • 2016-06-25
      • 2017-09-24
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多