為什么“=”在where子句中,不匹配精確的字串(包括空格和特殊字符)。
在此查詢中,我應用了“$”符號來過濾資料表上的重復資料,并將 null 視為空字串。此查詢將回傳組名稱前面的一組內所有值的總和。
問題是資料/字串有空格或特殊字符,如“。” 在其中它不會匹配 where 子句中的這些字串,并在這些組前面顯示 null 而不是它們的一些。
架構 (PostgreSQL v13)
CREATE TABLE IF NOT EXISTS products (
id int NOT NULL,
title varchar(200) NOT NULL,
description varchar(200) NOT NULL,
price int NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO products VALUES
(1, 'test', 'test',2222),
(2, 'test', 'test2',1111),
(3, 'test3', 'test3',1111),
(4, 'test3.2', 'test3.2',555),
(5, 'test3.2', 'test3.3',1111),
(6, 'test4', 'test4 desc',1111);
查詢 #1
create or replace function get_price_value(
tablename regclass,
sum_of_column_name character varying,
on_column_name character varying,
on_column_value text
)
returns int as
'
declare total_sum integer;
begin
EXECUTE FORMAT(''select sum(%I) from %I where %I=''''%I'''' ''
,sum_of_column_name
,tablename
,on_column_name
,on_column_value)
INTO total_sum;
return total_sum;
end;
'
language plpgsql;
沒有要顯示的結果。
查詢 #2
select id,
title,
description,
price
from(
select DISTINCT id, title, description, price,trno, drno
from (
select id, 1, null, title, null, get_price_value('products'::regclass,'price','title',title)::varchar as price, 1 as trno, 2 as drno from products
union all
select id, 2, null, concat(title,'$$$'), description, get_price_value('products'::regclass,'price','description',description)::varchar as price, 2 as trno, 1 as drno from products
union all
select id, 3, id::varchar, concat(title,'$$$') as title, concat(description,'$$$') as description, price::varchar, 2 as trno, 2 as drno from products
) temp1 (xid, xord, id, title, description,price,trno,drno)
order by title, trno, description, drno
) as temp2;
| ID | 標題 | 描述 | 價格 |
|---|---|---|---|
| 測驗 | 3333 | ||
| 測驗$$$ | 測驗 | 2222 | |
| 1 | 測驗$$$ | 測驗$$$ | 2222 |
| 測驗$$$ | 測驗2 | 1111 | |
| 2 | 測驗$$$ | 測驗2$$$ | 1111 |
| 測驗3 | 1111 | ||
| 測驗3$$$ | 測驗3 | 1111 | |
| 3 | 測驗3$$$ | 測驗3$$$ | 1111 |
| 測驗3.2 | |||
| 測驗3.2$$$ | 測驗3.2 | ||
| 4 | 測驗3.2$$$ | 測驗3.2$$$ | 555 |
| 測驗3.2$$$ | 測驗3.3 | ||
| 5 | 測驗3.2$$$ | 測驗3.3$$$ | 1111 |
| 測驗4 | 1111 | ||
| 測驗4$$$ | 測驗4描述 | ||
| 6 | 測驗4$$$ | test4 描述$$$ | 1111 |
資料表中的輸出視圖

預期輸出:

請在sql中提出任何解決方案。謝謝!
在 DB Fiddle 上查看
uj5u.com熱心網友回復:
問題是FORMAT(''where %I=''''%I'''' ''部分。第二個 %I 不是識別符號,而是一個文字,您應該使用 %L 而不使用封閉的 '。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497546.html
標籤:sql 数据库 PostgreSQL 排 where子句
