标签:
创建表:
CREATE TABLE countries( country_code char(2) PRIMARY KEY, country_name text UNIQUE );
插入数据:
INSERT INTO countries(country_code,country_name) VALUES (‘us‘,‘United States‘),(‘mx‘,‘Mexico‘),(‘au‘,‘Australia‘), (‘gb‘,‘United Kingdom‘),(‘de‘,‘Gemany‘),(‘ll‘,‘Loompaland‘);
或
INSERT INTO countries VALUES (‘us‘,‘United States‘),(‘mx‘,‘Mexico‘);
查询数据:
SELECT * FROM countries;
删除数据:
DELETE FROM countries WHERE country_code = ‘ll‘;
外键:为了保证cities中所有的country_code都在countries出现过,
所以给cities的country_code添加references外键约束。
CREATE TABLE cities( name text NOT NULL, postal_code varchar(9) CHECK(postal_code <> ‘‘), country_code char(2) REFERENCES countries, PRIMARY KEY (country_code,postal_code) );
但cities表的country_code引用可以为NULL,代表一个值空缺,
如果不允许cities.country_code为空,可以这样定义:
country_code char(2) REFERENCES countries NOT NULL
插入外键数据:
INSERT INTO cities VALUES (‘Portland‘,‘87200‘,‘us‘);
更新上面的数据:
UPDATE cities SET postal_code = ‘97205‘ WHERE name = ‘Portland‘;
使用联接查询:
SELECT cities.*,country_name FROM cities INNER JOIN countries ON cities.country_code = countries.country_code;
外键引用两个主键:
CREATE TABLE venues( venue_id SERIAL PRIMARY KEY, name varchar(255), street_address text, type char(7) CHECK (type in (‘public‘,‘private‘)) DEFAULT ‘public‘, postal_code char(2), country_code char(2), FOREIGN KEY (country_code,postal_code) REFERENCES cities(country_code,postal_code) MATCH FULL );
左外联接:
SELECT e.title,v.name FROM events e LEFT JOIN venues v ON e.venues_id = v.venues_id;
新建表时,postgresql会默认在主键上建立索引,
使用UNIQUE强制在一列上建立索引。
建立索引:
CREATE INDEX envents_title ON envents USING hash (title);
对于操作符为大于/小于/等于这样的匹配查询,使用B树索引,相当于汇编的段寄存器。
CREATE INDEX events_starts ON events USING btree (starts);
使用B树索引查询:
SELECT * FROM events WHERE starts >= ‘2012-04-01‘;
标签:
原文地址:http://www.cnblogs.com/liuxuzzz/p/5218527.html