SQL --初解

SQL初解

    • 建立数据库
    • sql语法
    • KEY字段值

建立数据库

第一步 使用postgresql建立数据库

// An highlighted block
[email protected]$ sudo -u postgres createuser --superuser $username
[email protected]$ sudo -u postgres createdb $databasename
[email protected]$ psql $databasename

sql语法

此时进入sql操作界面

databasename=# CREATE TABLE flights(  // 这里按回车,注意括号位置,flights 是你的tablename
databasename=# id SERIAL PRIMARY KEY,
databasename=# origin VARCHR NOT NULL,
databasename=# destination VARCHAR NOT NULL,
databasename=# duration INTEGER NOT NULL);
CREATE TABLE flights 
id SERIAL PRIMARY KEY,
origin VARCHR NOT NULL,
destination VARCHAR NOT NULL,
duration INTEGER NOT NULL

在sql里面输入

\d // 显示所创建的表

创建另外一张与第一章表有关系的表

CREATE TABLE passengers
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
flight_id INTEGER REFERENCES flights
databasename=# CREATE TABLE passengers(  // 这里按回车,注意括号位置,flights 是你的tablename
databasename=# id SERIAL PRIMARY KEY,
databasename=# name VARCHR NOT NULL,
databasename=# flight_id INTEGER REFERNENCES flights);
// 建立成功会有提示

注意 sql语句视 分号 ; 为结束标志,若无分号,则表示延续

INSERT INTO flights (orgin,destination,duration) VALUES ('New York','London',415); 
// 增加数据,flights是你的tablename

DELETE FROM countries WHERE destination = 'Tokyo

UPDATE flights //此处按回车,flights是你的tablename
	SET duration = $newvalue where origin = 'New York' AND destination = 'London';

// flights是你的tablename

//显示表各项性质
\d+ flights //Postgresql
DESCRIBLE flights // MySQL 或者 Oracle数据库

SELECT * FROM flights // 从flights表中取出所有数据,

SELECT origin from flights // 从flights表中取出orgrin 列数据,

SELECT origin,destination from flights //从flights表中取出origin和destination列数据,

SELECT * FROM flights where id = 2 // 根据id取出数据
 
SELECT * FROM flights where origin = 'Shanghai'; // 根据给定的自定义的字段值取出数据

SELECT * FROM flights LIMIT 2;  //仅仅显示两条数据

SELECT COUNT(*) FROM flights; // flights表中有几条数据

SELECT * FROM flights ORDER BY duration ASC; //按照duration的字母顺序进行排序

SELECT origin,COUNT(*) FROM flights GROUP BY origin; //显示orgin下的每一项及次数


SELECT origin,COUNT(*) FROM flights GROUP BY origin HAVING COUNT(*) > 1; 
//GROUP限定条件用HAVING
  • 这是查询的字段分布在两个表中时用此语句

目前来看两个表名字先后顺序不影响查询结果
SELECT origin,destination,name FROM flights JOIN passengers ON
passengers.flight_id = flights.id where name = 'Alice';
SELECT flights_id FROM passengers GROUP BY flight_id HAVING COUNT(*) > 1;

KEY字段值

你可能感兴趣的:(sql,sql)