Postgres查询在字符类型不同的数据类型中不适用于数值

时间:2018-06-20 12:50:48

标签: sql postgresql

这里我使用的是postgres 9.6,而PFA是我的postgres表模式

id  username
----------
1   ashesh 
2   123456

使用'123456'对用户名进行查询时,不会给出响应,但是使用“ ashesh”进行查询时,则会给出响应。我的查询是

select * from customer where username = '123456';

给我一​​个空白的答复,但是在查询“ ashesh”时

select * from customer where username = 'ashesh';

它将给出响应。

2 个答案:

答案 0 :(得分:1)

也许,有时您在用户名值中保留空白(似乎123456),

trim可以用于 username 列的where条件:

create table customer( ID int, username varchar(125));
insert into customer values(1,'ashesh');
insert into customer values(2,'123456 ');

create table customer( ID int, username varchar(125));
insert into customer values(1,'ashesh');
id  username
1   ashesh

select * from customer where trim(username) = 'ashesh';
1   ashesh

select * from customer where username = '123456';
--no results return

select * from customer where trim(username) = '123456';
id  username
2   123456

SQL Fiddle Demo

答案 1 :(得分:0)

您的问题似乎是隐藏的字符-在where常量中或在列本身中。如果是第一种,那么只需重新键入代码即可解决问题。

第二个需要更多调查。我将从以下内容开始:

where username like '%123456%'

查看是否有任何用户名包含该字符序列。如果找到该行,则开始寻找隐藏的字符。如果没有,请尝试:

where username like '%1%2%3%4%5%6%'

这将在数字之间寻找隐藏的字符。确定问题所在后,就可以找出解决问题的方法。

如果您有一组允许的固定字符,则还可以测试:

where regexp_replace(username, '[^a-zA-Z0-9]', '', 'g') = '123456'

如果这是问题所在,可以使用以下方法删除隐藏的字符:

update customer
    set username = regexp_replace(username, '[^a-zA-Z0-9]', '', 'g')
    where username ~ '[^a-zA-Z0-9]';
相关问题