简体   繁体   English

正则表达式:Postgres SQL查询返回表中所有可用的记录

[英]Regular expression: Postgres SQL query is returning all records available in the table

The below Postgres SQL query is returning all records available in the table. 下面的Postgres SQL查询返回表中所有可用的记录。 Can someone give explanation for this? 有人可以解释一下吗? . Also please let me know what * represents in case of postgres regular expression. 另外请让我知道在Postgres正则表达式中*代表什么。

Employee table contains :

name
Chennai
Delhi
Hydrabad
NewYark
ABC

select * from employee where name ~ 'Z*'

This is the correct query for finding name starting with 'Z' : 这是查找以'Z'开头的名称的正确查询:

SELECT record FROM myrecords WHERE name ~ '^Z';

in your query : 在您的查询中:

select * from employee where name ~ 'Z*'

the meaning is where the name matches ZERO or MORE sequences of character "Z", hence returning all records. 含义是名称与字符“ Z”的零或更多序列匹配,从而返回所有记录。

  • * in the matching criteria means ZERO or MORE occurences. 匹配条件中的*表示零次或多次发生。

  • * along with tilda means case insensitive match ie ~* 'Z' will match both "z" and "Z" *和tilda一起表示不区分大小写的匹配,即〜*'Z'将同时匹配“ z”和“ Z”

For more have a look here : 更多信息请看这里:

http://oreilly.com/pub/a/databases/2006/02/02/postgresq_regexes.html?page=1 http://oreilly.com/pub/a/databases/2006/02/02/postgresq_regexes.html?page=1

The * quantifier means zero or more . *量词表示零或更大 Since every name contains at least zero Z characters, every row is returned. 由于每个名称至少包含零个Z字符,因此将返回每一行。

You don't need to use a regex to find strings starting with a character, you can just use LIKE : 您不需要使用正则表达式来查找以字符开头的字符串,只需使用LIKE

SELECT record FROM myrecords WHERE name LIKE 'Z%';

If you want names starting with Z using a regex , try this: 如果要使用正则表达式以Z开头的名称,请尝试以下操作:

SELECT record FROM myrecords WHERE name ~ '^Z';

If you want names containing at least one Z, try one of these: 如果您想要包含至少一个Z的名称,请尝试以下方法之一:

SELECT record FROM myrecords WHERE name LIKE '%Z%';
SELECT record FROM myrecords WHERE name ~ 'Z';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM