执行环境: psql
1. 创建一个表格
CREATE TABLE customers (
customer_id serial PRIMARY KEY,
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(100) NOT NULL,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_on TIMESTAMPTZ NOT NULL
);
- customer_id:这是一个序列,意味着它将自动递增,用作主键,用来唯一标识每个客户。
- created_on:这是一个不允许为空的日期时间字段,用来存储客户的创建时间。
2. 插入
INSERT INTO customers(firstname, lastname, username, password, email, created_on)
VALUES('Elizabeth', 'Banks', 'elizabethbanks', '4s$5eks9m', 'elizabethbanks@myemail.com', CURRENT_TIMESTAMP);
SELECT * FROM customers;
插入两条记录
INSERT INTO customers(firstname, lastname, username, password, email, created_on)
VALUES('Nicole', 'Kidman', 'nkidman', '392kMLK!m', 'nicole@kidman.com', CURRENT_TIMESTAMP),
('Leroy', 'Jenkins', 'leeroy', '4k2ln@Lm', 'leroy@email.com', CURRENT_TIMESTAMP);
SELECT * FROM customers;
3. 修改
UPDATE customers
SET username='aliceinwonderland'
WHERE email=
'elizabethbanks@myemail.com';
SELECT * FROM customers;
4. 查找
SELECT * FROM customers WHERE username='aliceinwonderland';
仅当"email"字段的值满足特定模式时才被选择,这个模式是以"@myemail.com"结尾的,而"%"符号表示可以有零个或多个字符。
SELECT username FROM customers WHERE email LIKE '%@myemail.com';
利用选择的数据创建一个新表
CREATE TABLE usernames AS SELECT username FROM customers WHERE email LIKE '%@myemail.com';
5. 排序
选择的数据将按照"lastname"字段进行降序排列
SELECT firstname, lastname
FROM customers
ORDER BY lastname DESC;
返回的结果将会包含每个客户的完整姓名、邮箱地址以及密码的长度,并且按照密码长度从短到长进行排序。
SELECT firstname || ' ' || lastname fullname, email, LENGTH(password) passwordlength
FROM customers
ORDER BY passwordlength;
选择 password 长度小于9的数据
SELECT firstname || ' ' || lastname fullname, email, LENGTH(password) passwordlength
FROM customers
WHERE LENGTH(password) < 9
ORDER BY passwordlength;
6. 删除
使用RETURNING关键字,返回受影响的行。
DELETE FROM customers
WHERE customer_id = 1
RETURNING *;
从"customers"表中删除"username"字段不等于’nkidman’的行
DELETE FROM customers
WHERE username <> 'nkidman'
RETURNING *;
从"customers"表中删除所有行。
DELETE FROM customers
RETURNING *;
7. 创建只读用户
该用户的有效期截止到’2024-02-02’。
CREATE USER readitralph
WITH PASSWORD 'password'
VALID UNTIL '2024-02-02';
授予名为"readitralph"的用户对数据库中所有数据的读取权限。
GRANT pg_read_all_data TO readitralph;