tip 1

在sql中我们可以设置一个列自增长identity(1,1),但在postgresql中却没有这个关键字定义。但postgresql也有实现相关功能,那就是只需要将该列数据类型标记为serial,就可以实现sql中的自增长功能

   

smallserial 2 bytes small autoincrementing integer 1 to 32767
serial 4 bytes autoincrementing integer 1 to 2147483647
bigserial 8 bytes large autoincrementing integer 1 to 9223372036854775807

tips 2

 对于postgresql中的部分系统表,有个唯一表示Row identifier 行标识符,(hidden attribute; must be explicitly selected),是一个隐藏的字段,只有显示调用才能显示,比如select oid,* from pg_class

 tips 3  

postgresql中case when 语法和sql 差不多。

SELECT 
CASE WHEN atttypid=23 THEN true
ELSE false
END as hehe, * from pg_attribute 
where attrelid='90330'

tip 4

postgressql中的自增长用serial存储,但是在数据库中是以默认值的形式实现的,用nextvalue函数,可以在pg_attrdef表中查出值

tip 5

postgresql字符串拼接函数,字符串拼接语法

string || string text String concatenation 'Post' || 'greSQL' PostgreSQL

tip 6

 对于数组可以用unnest函数化为多行然后left join,例如select * from pg_index对于系统的索引表中 indkey字段,对于复合主键就需要化为多行然后关联

unnest(anyarray) setof anyelement expand an array to a set of rows unnest(ARRAY[1,2])
1
2
(2 rows)

tip7    sql中添加表的时候对于以下敏感字可以加上方括号,而在postgresql中,对于敏感字需要加上双引号如

create table "Table" ( 
Id serial not null ,
PointCode varchar(32) 
);

tip8

PostgreSQL中像numeric这样的包含长度和精度的数据类型被存储在系统表pg_attribute里面,但是并没有单独存放这个字段的值,而是通过一个函数转化为一个整数存放在里面atttypmod,这样当我们直接到系统表取值的时候就不得不将其重新转化为精度和长度。转换方法如下。

SELECT
  CASE atttypid
         WHEN 21 /*int2*/ THEN 16
         WHEN 23 /*int4*/ THEN 32
         WHEN 20 /*int8*/ THEN 64
         WHEN 1700 /*numeric*/ THEN
              CASE WHEN atttypmod = -1
                   THEN null
                   ELSE ((atttypmod - 4) >> 16) & 65535     -- calculate the precision
                   END
         WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
         WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
         ELSE null
  END   AS numeric_precision,
  CASE 
    WHEN atttypid IN (21, 23, 20) THEN 0
    WHEN atttypid IN (1700) THEN            
        CASE 
            WHEN atttypmod = -1 THEN null       
            ELSE (atttypmod - 4) & 65535            -- calculate the scale  
        END
       ELSE null
  END AS numeric_scale,
  *
FROM 
    pg_attribute ;

tip9  

postgresql c#操作类库  Npgsql ( .NET 连接到 PostgreSQL 数据库的驱动程序) 

  NpgSql连接字符串:

 

//远程连接模式
Server=127.0.0.1;Port=5432;Database=myDataBase;User Id=myUsername;
Password=myPassword;
PostgreSQL
//本地连接模式
Server=127.0.0.1;Port=5432;Database=myDataBase;Integrated Security=true;

 另:https://connectionstrings.com/下有几乎所有连接数据库的连接字符串例子

 

tip10     select  from customertype LIMIT num  OFFSET startNum  和mysql一样这样可以实现sql中的top 功能。另外postgresql不支持

错误:  不支持 LIMIT #,# 语法

tip11    http://www.neilconway.org/docs/sequences/

test=# CREATE TABLE users (
test(#     id    SERIAL, -- assign each user a numeric ID
test(#     name  TEXT,
test(#     age   INT4
test(# );
NOTICE:  CREATE TABLE will create implicit sequence
"users_id_seq" for serial column "users.id"
CREATE TABLE
CREATE TABLE users (
    -- make the "id" column a primary key; this also creates
    -- a UNIQUE constraint and a b+-tree index on the column
    id    SERIAL PRIMARY KEY,
    name  TEXT,
    age   INT4
);

Usage example:

INSERT INTO users (name, age) VALUES ('Mozart', 20);

Or equivalently:

INSERT INTO users (name, age, id) VALUES ('Mozart', 20, DEFAULT);

SELECT currval(pg_get_serial_sequence('users', 'id'));

pg_exec("INSERT INTO users (name, age) VALUES ('Bach', 15);
         SELECT currval(pg_get_serial_sequence('users', 'id'));")

INSERT INTO users (name, age) VALUES ('Liszt', 10) RETURNING id;

tip11 postgresql 对大小写敏感
http://blog.csdn.net/huguangshanse00/article/details/8521008
http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=812899
http://blog.sina.com.cn/s/blog_4fb490ff01012g5f.html

由于PostgreSQL 是大小写敏感的,并默认对SQL语句中的数据库对象名称转换为小写,因此如果你在创建数据库对象时指定了大小写混和的对象名称,那么在通过SQL语句访问这些对象时,必须使用双引号(")将数据库对象括起来,以提示 PostgreSQL 不用帮你转换对象名为小写,否则将激发“xxxxx对象不

存在”的异常,譬如您的数据库中有名为 TUser 的表,您在 PostgreSQL 自带的图形化查询工具中必须使用类似这样的查询语句才能正确执行:SELECT * FROM "TUser",当然它对 SQL 标准中的保留字和关键字是不区分大小写的,所以写成 select * From "TUser" 这样也是完全可以的。

 

  另外,PostgreSQL对数据也是大小写敏感的,这点与 SQLServer 不同(SQLServer默认是不敏感的),譬如在 TUser 表中有字段 Name,其中有一行 Name 字段值为“Tony Tang”的记录,如果直接使用

SELECT* FROM "TUser" WHERE "Name" LIKE '%tony%';

是查询不到这条记录的,不过你可以这么写:

SELECT* FROM "TUser" WHERE UPPER("Name") LIKE '%TONY%';

  呵呵,是不是觉得这样不太好看,而且担心性能会受影响?幸好 PostgreSQL 提供了关键字ILIKE来帮我们解决这个问题,这真是个非常有趣的关键字(Ilike),对于第一种写法只需要将 LIKE 替换成ILIKE 就可以了。

    最后,建议在编写 SQL脚本的时候,使用单引号做字符串常量的标识,虽然在 MS SQLServer 中双引号和单引号均可作为字符串常量的标识符,但是在 PostgreSQL 中对此就有严格的功能区分(不能用双引号作为字符串常量的标识符),为了保险起见,建议对所有的数据库对象名均使用双引号(")将其显式约定,以保证大小写的严格匹配。

评论:

一.对象名:如表名,字段名

数据库内核是区分大小写的。

只是为了方便使用,数据库在分析SQL脚本时,对不加双引号的所有对象名转化为小写字母。

除非你在对象名加上双引号。

所以

1。从建表到应用,要么都加双引号,要么都不要加。

2。如果以上这点做不到,所有的对象名给我写小写字母。

 

二.数据

区分大小写

假如LIKE '%a%',别指望A会出来

函数返回类型描述例子结果
string || string text 字串连接 'Post' || 'greSQL' PostgreSQL
bit_length(string) int 字串里二进制位的个数 bit_length('jose') 32
char_length(string) 或character_length(string) int 字串中的字符个数 char_length('jose') 4
convert(string using conversion_name) text 使用指定的转换名字改变编码。转换可以通过 CREATE CONVERSION 定义。当然系统里有一些预定义的转换名字。参阅 Table 9-7 获取可用的转换名。 convert('PostgreSQL' using iso_8859_1_to_utf8) UTF8 (Unicode, 8 位)编码的'PostgreSQL'
lower(string) text 把字串转化为小写 lower('TOM') tom
octet_length(string) int 字串中的字节数 octet_length('jose') 4
overlay(string placing string from int[for int]) text 替换子字串 overlay('Txxxxas' placing 'hom' from 2 for 4) Thomas
position(substring in string) integer 指定的子字串的位置 position('om' in 'Thomas') 3
substring(string [from int] [for int]) text 抽取子字串 substring('Thomas' from 2 for 3) hom
substring(string from pattern) text 抽取匹配 POSIX 正则表达式的子字串 substring('Thomas' from '...$') mas
substring(string from pattern for escape) text 抽取匹配SQL正则表达式的子字串 substring('Thomas' from '%#"o_a#"_' for '#') oma
trim([leading | trailing | both] [characters] from string) text 从字串 string 的 开头/结尾/两边/ 删除只包含 characters (缺省是一个空白)的最长的字串 trim(both 'x' from 'xTomxx') Tom
upper(string) text 把字串转化为大写。 upper('tom') TOM

其中查看了很多的相关博客,我也来总结一下PostgreSQL里面的字符串相关的函数吧!

select replace('wangfumin',  'an',  'iu')

函数:string || string 
说明:String concatenation 字符串连接操作
例子:select 'Post' || 'greSQL'; = PostgreSQL

 

函数:string || non-string or non-string || string
说明:String concatenation with one non-string input 字符串与非字符串类型进行连接操作
例子:select 'Value: ' || 42; = Value: 42

 

函数:bit_length(string)
说明:Number of bits in string 计算字符串的位数
例子:select bit_length('pmars') = 40

 

函数:char_length(string) or character_length(string)
说明:Number of characters in string 计算字符串中字符个数
例子:select char_length('pmars'); = 5

 

函数:lower(string)
说明:Convert string to lower case 转换字符串为小写
例子:select lower('PmArS'); = "pmars"

 

函数:octet_length(string)
说明:Number of bytes in string 计算字符串的字节数
例子:select octet_length('我是pmars'); = 11  select octet_length('我');  = 3


函数:overlay(string placing string from int [for int])
说明:Replace substring 替换字符串中任意长度的子字串为新字符串
例子:select overlay('I am pmars' placing 'ming' from 6 for 5); = "I am ming"


函数:position(substring in string)
说明:Location of specified substring 子串在一字符串中的位置
例子:select position('ma' in 'pmars'); = 2


函数:substring(string [from int] [for int])
说明:Extract substring 截取任意长度的子字符串
例子:select substring('topmars' from 3 for 3); = "pma"


函数:substring(string from pattern)
说明:Extract substring matching POSIX regular expression. See Section 9.7 for more information on pattern matching. 利用正则表达式对一字符串进行任意长度的字串的截取
例子:select substring('topmars' from 'p.*$'); = "pmars"


函数:substring(string from pattern for escape)
说明:Extract substring matching SQL regular expression. See Section 9.7 for more information on pattern matching. 利于正则表达式对某类字符进行删除,以得到子字符串
例子:select substring('Thomas' from '%#"o_a#"_' for '#'); = "oma"


函数:trim([leading | trailing | both] [characters] from string) 
说明:Remove the longest string containing only the characters (a space by default) from the start/end/both ends of the string 去除尽可能长开始,结束或者两边的某类字符,默认为去除空白字符,当然可以自己指定,可同时指定多个要删除的字符串
例子:select trim(leading 'p' from 'pmars'); = "mars"


函数:upper(string)
说明:Convert string to uppercase 将字符串转换为大写
例子:select upper('pmars'); = "PMARS"


函数:ascii(string)
说明:ASCII code of the first character of the argument. For UTF8 returns the Unicode code point of the character. For other multibyte encodings. the argument must be a strictly ASCII character. 得到某一个字符的Assii值
例子:select ascii('pmars'); = select ascii('p'); = 112


函数:btrim(string text [, characters text])
说明:Remove the longest string consisting only of characters in characters (a space by default) from the start and end of string 去除字符串两边的所有指定的字符,可同时指定多个字符
例子:select btrim('pmars','prs'); = "ma"


函数:chr(int)
说明:Character with the given code. For UTF8 the argument is treated as a Unicode code point. For other multibyte encodings the argument must designate a strictly ASCII character. The NULL (0) character is not allowed because text data types cannot store such bytes. 得到某ACSII值对应的字符
例子:select chr(65); = A


函数:convert(string bytea, src_encoding name, dest_encoding name) 
说明:Convert string to dest_encoding. The original encoding is specified by src_encoding. The string must be valid in this encoding. Conversions can be defined by CREATE CONVERSION. Also there are some predefined conversions. See Table 9-7 for available conversions. 转换字符串编码,指定源编码与目标编码
例子:select convert('我是pmars_in_utf8', 'UTF8', 'GBK'); = "\316\322\312\307pmars_in_utf8"


函数:convert_from(string bytea, src_encoding name) 
说明:Convert string to the database encoding. The original encoding is specified by src_encoding. The string must be valid in this encoding. 转换字符串编码,自己要指定源编码,目标编码默认为数据库指定编码,
例子:select convert_from('\316\322\312\307pmars','GBK'); = "我是pmars"


函数:convert_to(string text, dest_encoding name) 
说明:Convert string to dest_encoding.转换字符串编码,源编码默认为数据库指定编码,自己要指定目标编码,
例子:select convert_to('我是pmars_in_utf8','GBK'); = "\316\322\312\307pmars_in_utf8"


函数:decode(string text, type text) 
说明:Decode binary data from string previously encoded with encode. Parameter type is same as in encode. 对字符串按指定的类型进行解码
例子:select decode('MTIzAAE=', 'base64'); = "123\000\001"


函数:encode(data bytea, type text) 
说明:Encode binary data to different representation. Supported types are: base64, hex, escape. Escape merely outputs null bytes as \000 and doubles backslashes. 与decode相反,对字符串按指定类型进行编码
例子:select encode('123\000\001','base64'); = "MTIzAAE="


函数:initcap(string)
说明:Convert the first letter of each word to uppercase and the rest to lowercase. Words are sequences of alphanumeric characters separated by non-alphanumeric characters. 将字符串所有的单词进行格式化,首字母大写,其它为小写
例子:select initcap('I AM PMARs'); = "I Am Pmars"


函数:length(string)
说明:Number of characters in string 讲算字符串长度
例子:select length('我是pmars'); = 7


函数:length(stringbytea, encoding name )
说明:Number of characters in string in the given encoding. The string must be valid in this encoding. 计算字符串长度,指定字符串使用的编码
例子:select length('我是pmars','GBK'); = 8


函数:lpad(string text, length int [, fill text]) 
说明:Fill up the string to length length by prepending the characters fill (a space by default). If the string is already longer than length then it is truncated (on the right). 对字符串左边进行某类字符自动填充,即不足某一长度,则在左边自动补上指定的字符串,直至达到指定长度,可同时指定多个自动填充的字符
例子:select lpad('pmars', 10, 'to'); = "tototpmars"


函数:ltrim(string text [, characters text]) 
说明:Remove the longest string containing only characters from characters (a space by default) from the start of string 删除字符串左边某一些的字符,可以时指定多个要删除的字符
例子:select ltrim('pmars','amp'); = "rs"


函数:md5(string)
说明:Calculates the MD5 hash of string, returning the result in hexadecimal 将字符串进行md5编码
例子:select md5('pmars'); = "1018ceb949f1472f7252f7da1f5eff42"


函数:pg_client_encoding()
说明:Current client encoding name 得到pg客户端编码
例子:select pg_client_encoding(); = "UTF8"


函数:quote_ident(string text)
说明:Return the given string suitably quoted to be used as an identifier in an SQL statement string. Quotes are added only if necessary (i.e., if the string contains non-identifier characters or would be case-folded). Embedded quotes are properly doubled. 对某一字符串加上两引号
例子:quote_ident('Foo bar') = "Foo bar"


函数:quote_literal(string text)
说明:Return the given string suitably quoted to be used as a string literal in an SQL statement string. Embedded single-quotes and backslashes are properly doubled. 对字符串里两边加上单引号,如果字符串里面出现sql编码的单个单引号,则会被表达成两个单引号
例子:quote_literal('O\'Reilly') = 'O''Reilly'


函数:quote_literal(value anyelement)
说明:Coerce the given value to text and then quote it as a literal. Embedded single-quotes and backslashes are properly doubled. 将一数值转换为字符串,并为其两边加上单引号,如果数值中间出现了单引号,也会被表示成两个单引号
例子:quote_literal(42.5) = '42.5'


函数:regexp_matches(string text, pattern text [, flags text])
说明:Return all captured substrings resulting from matching a POSIX regular expression against the string. See Section 9.7.3 for more information. 对字符串按正则表达式进行匹配,如果存在则会在结果数组中表示出来
例子:regexp_matches('foobarbequebaz', '(bar)(beque)') = {bar,beque}


函数:regexp_replace(string text, pattern text, replacement text [, flags text])
说明:Replace substring(s) matching a POSIX regular expression. See Section 9.7.3 for more information. 利用正则表达式对字符串进行替换
例子:regexp_replace('Thomas', '.[mN]a.', 'M') = ThM


函数:regexp_split_to_array(string text, pattern text [, flags text ])
说明:Split string using a POSIX regular expression as the delimiter. See Section 9.7.3 for more information. 利用正则表达式将字符串分割成数组
例子:regexp_split_to_array('hello world', E'\\s+') = {hello,world}


函数:regexp_split_to_table(string text, pattern text [, flags text])
说明:Split string using a POSIX regular expression as the delimiter. See Section 9.7.3 for more information. 利用正则表达式将字符串分割成表格
例子:regexp_split_to_table('hello world', E'\\s+') = 
hello
world
(2 rows)


函数:repeat(string text, number int)
说明:Repeat string the specified number of times 重复字符串一指定次数
例子:repeat('Pg', 4) = PgPgPgPg


函数:replace(string text, from text, to text)
说明:Replace all occurrences in string of substring from with substring to 将字符的某一子串替换成另一子串
例子:('abcdefabcdef', 'cd', 'XX') = abXXefabXXef


函数:rpad(string text, length int [, fill text]) 
说明:Fill up the string to length length by appending the characters fill (a space by default). If the string is already longer than length then it is truncated. 对字符串进行填充,填充内容为指定的字符串
例子:rpad('hi', 5, 'xy') = hixyx


函数:rtrim(string text [, characters text])
说明:Remove the longest string containing only characters from characters (a space by default) from the end of string 
去除字符串右边指定的字符
例子:rtrim('trimxxxx', 'x') = trim


函数:split_part(string text, delimiter text, field int)
说明:Split string on delimiter and return the given field (counting from one)  对字符串按指定子串进行分割,并返回指定的数值位置的值
例子:split_part('abc~@~def~@~ghi''~@~', 2) = def


函数:strpos(string, substring)
说明:Location of specified substring (same as position(substring in string), but note the reversed argument order) 指定字符串在目标字符串的位置
例子:strpos('high', 'ig') = 2


函数:substr(string, from [, count])
说明:Extract substring (same as substring(string from from for count)) 截取子串
例子:substr('alphabet', 3, 2) = ph


函数:to_ascii(string text [, encoding text])
说明:Convert string to ASCII from another encoding (only supports conversion from LATIN1, LATIN2, LATIN9, and WIN1250 encodings) 将字符串转换成ascii编码字符串
例子:to_ascii('Karel') = Karel


函数:to_hex(number int or bigint)
说明:Convert number to its equivalent hexadecimal representation  对数值进行十六进制编码
例子:to_hex(2147483647) = 7fffffff


函数:translate(string text, from text, to text) 
说明:Any character in string that matches a character in the from set is replaced by the corresponding character in the to set 将字符串中某些匹配的字符替换成指定字符串,目标字符与源字符都可以同时指定多个
例子:translate('12345', '14', 'ax') = a23x5

参考  stackoverflow

参考:http://blog.163.com/digoal@126/blog/static/163877040201371763839672/

参考:https://connectionstrings.com/postgresql/

本文地址:http://www.cnblogs.com/santian/p/4362679.html

博客地址:http://www.cnblogs.com/santian/

转载请以超链接形式标明文章原始出处。
posted on 2015-03-24 17:42  一天两天三天  阅读(2479)  评论(0编辑  收藏  举报