gpt4 book ai didi

postgresql - 如何管理 sql 查询中的 NULL 字符串或日期 (PostgreSQL)

转载 作者:行者123 更新时间:2023-11-29 13:10:07 25 4
gpt4 key购买 nike

PostgreSQL 11.1 对于下面的 sql 查询,其中 $1 和 $2 是字符串,$3 是时间戳,如何重写下面的查询,以便 $3 中的空值允许选择每个日期(不仅仅是空日期)。

   SELECT lastname, firstname, birthdate FROM patients 
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'%' AND birthdate::date = $3::date
UNION
SELECT lastname, firstname, birthdate FROM appointment_book
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'$' and birthdate::date = $3::date

也就是说,如果 $3 为 null,那么这应该减少为:

SELECT lastname, firstname, birthdate FROM patients 
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'%'
UNION
SELECT lastname, firstname, birthdate FROM appointment_book
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'$'

最佳答案

未经测试,但我认为您可以使用 CASE 表达式来处理它

SELECT lastname, firstname, birthdate FROM patients p
WHERE UPPER(p.lastname) LIKE UPPER($1)||'%'
AND UPPER(p.firstname) LIKE UPPER($2)||'%'
AND (CASE WHEN $3 IS NULL THEN TRUE
ELSE p.birthdate::date = $3::date
END)
UNION
SELECT lastname, firstname, birthdate FROM appointment_book ab
WHERE UPPER(ab.lastname) LIKE UPPER($1)||'%'
AND UPPER(ab.firstname) LIKE UPPER($2)||'%'
AND (CASE WHEN $3 IS NULL THEN TRUE
ELSE ab.birthdate::date = $3::date
END);

关于postgresql - 如何管理 sql 查询中的 NULL 字符串或日期 (PostgreSQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56050564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com