postgre- 常用基本sql 语句

来源:互联网 发布:淘宝买家信誉查询工具 编辑:程序博客网 时间:2024/04/30 08:17
查看当前使用postgrs 的版本
select version();

查看当前日期
select current_date;

postgres 的psql:(执行psql就可以进入以下的命令模式,可以使用man psql查看帮助文档)
postgres 的命令以“\”开头.提升了很多的SQL命令如下:
显示帮助文档:
mydb=> \h

离开psql命令模式:
mydb=> \q

创建数据表
CREATE TABLE weather (
city varchar(80),
temp_lo int, -- low temperature
temp_hi int, -- high temperature
prcp real, -- precipitation
date date
);

CREATE TABLE cities (
name varchar(80),
location point
);
插入数据:
INSERT INTO weather VALUES (’San Francisco’, 46, 50, 0.25, ’1994-11-27’);
INSERT INTO cities VALUES (’San Francisco’, ’(-194.0, 53.0)’);
上面的写法要知道列的顺序,下面的写法可以根据我们自己列出的列的顺序进行插入值
INSERT INTO weather (city, temp_lo, temp_hi, prcp, date)
VALUES (’San Francisco’, 43, 57, 0.0, ’1994-11-29’);
INSERT INTO weather (date, city, temp_hi, temp_lo)
VALUES (’1994-11-29’, ’Hayward’, 54, 37);

COPY weather FROM ’/home/user/weather.txt’;

查询表

和很多数据库一样*代表显示所有的列。
select * from weather;

指定显示列查询
select city,temp_lo,temp_hi,prcp,date from weather;
  city  | temp_lo | temp_hi | prcp |    date   
--------+---------+---------+------+------------
 fujian |      46 |      50 | 0.25 | 2015-12-25
 fujian |      31 |      12 |    0 | 2015-12-24

可以对列数据进行运算显示
 SELECT CITY,(TEMP_LO+TEMP_HI)/2 AS TEMP_AVG,DATE FROM WEATHER;
  city  | temp_avg |    date   
--------+----------+------------
 fujian |       48 | 2015-12-25
 fujian |       21 | 2015-12-24
注:postgres 是不区分大小写的。
条件查询
select * from weather where city='fujian' and prcp > 0.0;
按照列排序
select * from weather order by city,temp_lo;
--插入测试数据
insert into weather(city,temp_lo,temp_hi,prcp,date)values
 ('jiangxi',10,40,3.5,'2015-12-24');

 insert into weather(city,temp_lo,temp_hi,prcp,date)values
('guangdong',14,40,2.0,'2015-12-24');
--取出city 字段去除重复
select distinct city from weather;
   city   
-----------
 fujian
 guangdong
 jiangxi

连接查询:(内连接)
--写法一:
select * from weather,cities where city=name;
  city  | temp_lo | temp_hi | prcp |    date    |  name  | location 
--------+---------+---------+------+------------+--------+-----------
 fujian |      46 |      50 | 0.25 | 2015-12-25 | fujian | (-194,53)
 fujian |      31 |      12 |    0 | 2015-12-24 | fujian | (-194,53)

--写法二:
SELECT weather.city, weather.temp_lo, weather.temp_hi,
weather.prcp, weather.date, cities.location
FROM weather, cities
WHERE cities.name = weather.city;
--写法三:
SELECT
*
FROM weather INNER JOIN cities ON (weather.city = cities.name);


0 0
原创粉丝点击