PostgreSQL简单使用
1、在windows中创建用户和数据库:
首先创建用户
template1=# CREATE USER rick WITH CREATEDB PASSWORD 'apress4789';
CREATE USER
template1=#
使用你新建的用户连接到数据库:
template1=# \c template1 rick
Password:
template1=#
是建立 bpsimple 数据库:
template1=> CREATE DATABASE bpsimple;
CREATE DATABASE
template1=>
使用新用户重新连接到 bpsimple 数据库:
template1=> \c bpsimple rick
You are now connected to database "bpsimple" as user "rick".
bpsimple=>
然后就可以创建表了。
2、一些基本的psql命令
\? 获得帮助消息
\do 列出操作类型
\dt 列出表
\dT 列出类型
\h <cmd> 列出 SQL 命令的帮助;用实际的命令代替<cmd>
\i <filename> 执行文件<filename>里头的命令
\r 重置缓冲器(忽略任何输入·····)
\q 退出 psql
3、PostgreSQL 有一个非 SQL 标准的 SELECT 语句的扩展从句,LIMIT,在我们想限制返回的行数时使用。在你的SELECT 语句后面添加一个带数字的 LIMIT 从句,从第一行开始,只有最多你指定的行数的行将被返回。使用 LIMIT 的另一个稍微不同的方法是在与指定开始位置的 OFFSET 从句一起使用的时候。
SELECT customer_id, town FROM customer LIMIT 5 OFFSET 2;
以上查询语句的意思是从查询结果中返回从第二行开始之后5行的数据。
4、PostgreSQL 中也是使用 IS NULL和IS NOT NULL来进行空值的判断
5、标准的比较运算符:
< 小于
<= 小于或等于
= 等于
>= 大于或等于
> 大于
<> 不等于
6、日期和时间的函数
date_part(units required, value to use) 允许你提取出日期的某一部分,例如月份。
Now 很简单地获得当前的日期和时间,它实际上和更标准的“变量”current_timestamp 相等。
其中data_part()的用法是:假设我们想要从我们的 orderinfo 表取出在九月下订单的行:
bpsimple=> SELECT * FROM orderinfo WHERE date_part('month',date_placed)=9;
orderinfo_id | customer_id | date_placed | date_shipped | shipping
--------------+-------------+-------------+--------------+----------
3 | 15 | 02-09-2004 | 12-09-2004 | 3.99
4 | 13 | 03-09-2004 | 10-09-2004 | 2.99
(2 rows)
bpsimple=>
PostgreSQL 为我们提取出了正确的行。注意日期是按照 ISO 格式显示的。我们可以提取日期和时间戳的以下部分:
Year(年)
Month(月)
Day(日)
Hour(小时)
Minute(分钟)
Second(秒钟)
也可以使用用于数字比较的<>,<=,<,>,>=和=运算符来比较日期,以下是一个示例:
bpsimple=> SELECT * FROM orderinfo WHERE date_placed >= cast('2004 07 21' AS date);
orderinfo_id | customer_id | date_placed | date_shipped | shipping
--------------+-------------+-------------+--------------+----------
3 | 15 | 02-09-2004 | 12-09-2004 | 3.99
4 | 13 | 03-09-2004 | 10-09-2004 | 2.99
5 | 8 | 21-07-2004 | 24-07-2004 | 0.00
(3 rows)
bpsimple=>
另外一个now函数的用法是:
bpsimple=> SELECT now(), current_timestamp;
now | timestamptz
------------------------------------+------------------------------------
Sat 16 Oct 13:46:05.99938 2004 BST | Sat 16 Oct 13:46:05.99938 2004 BST
(1 row)
bpsimple=>
可以对日期进行简单的计算。例如,计算从下订单到发货所间隔的天数:
bpsimple=> SELECT date_shipped - date_placed FROM orderinfo;
?column?
---------
4
1
10
7
3
(5 rows)
bpsimple=>