【问题标题】:Choose the part after WHERE depending on the parameter passed in SQL query根据SQL查询传入的参数选择WHERE后面的部分
【发布时间】:2019-07-19 08:38:45
【问题描述】:

我需要根据传递的参数替换查询条件来选择记录数

我写了 2 个查询,但不知道如何在 1 中组合

如果 parent_uid 为 null 我需要执行:

SELECT count(*) FROM TABLE WHERE 
parent_uid IS null AND name = 
:name AND tenant_uid = :tenant_uid;

其他:

SELECT count(*) FROM TABLE WHERE 
parent_uid = :parent_uid AND name = 
:name AND tenant_uid = :tenant_uid

这是我需要的伪代码

IF parent_uid IS null 
THEN SELECT count(*) FROM TABLE WHERE parent_uid IS null AND name = :name AND tenant_uid = :tenant_uid

ELSE SELECT count(*) FROM TABLE WHERE parent_uid = :parent_uid AND name = :name AND tenant_uid = :tenant_uid END IF;
/**
 * returns the count of categories that contain all parameters passed
 * @param name category name
 * @parm parentUid parent category uid
 * @param tenantUid tenant uid
 * @return count of records
 */
public int checkCategoryUniqueName(UUID parentUid, String name, UUID tenantUid)
{
    MapSqlParameterSource map = new MapSqlParameterSource()
            .addValue(PARENT_UID_PARAMETER, parentUid)
            .addValue(NAME_PARAMETER, name)
            .addValue(TENANT_UID_PARAMETER, tenantUid);

    return jdbcTemplate.queryForObject(GET_ECATEGORY_COUNT, map , Integer.class);
}

【问题讨论】:

  • WHERE (parent_uid IS null or parent_uid = :parent_uid)?
  • @a_horse_with_no_name 我认为 IS NULL 比较仅在 :parent_uid 为空(未给出)时才有效。也许OP可以澄清这一点。
  • 你能告诉我们你调用这个 SQL 查询的 Java 代码吗?
  • @JoakimDanielson:IF 语句检查列名,而不是参数,所以我不确定(我认为参数和列使用相同的名称会使事情变得非常混乱)
  • @deHaar 是的,我添加了

标签: java sql postgresql


【解决方案1】:

不需要ifs。

WHERE (:parent_uid IS NULL AND parent_uid IS NULL) OR (parent_uid=:parent_uid)

【讨论】:

    【解决方案2】:

    你最好用你的语言(我猜是 Java)构造正确的 SQL 字符串。

    String sqlParentUid = " parent_uid IS null "
    if (parentUid != null) { // parentUid from function
        sqlParentUid = " parent_uid = " + parentUid.toString()
    }
    

    然后只需将此部分添加到基本 sql 并运行查询

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多