【发布时间】: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