表达式是由一个或多个的值、运算符、PostgresSQL 函数组成的。
PostgreSQL 表达式类似一个公式,我们可以将其应用在查询语句中,用来查找数据库中指定条件的结果集。
SELECT 语句的语法格式如下:
SELECT column1, column2, columnN FROM table_name WHERE [CONDITION | EXPRESSION];
PostgreSQL 的表达式可以有不同类型,我们接下来会讲到。
布尔表达式是根据一个指定条件来读取数据:
SELECT column1, column2, columnN FROM table_name WHERE SINGLE VALUE MATCHTING EXPRESSION;
COMPANY.SQL文件内容如下:
-- This is the file to create COMPANY table and to populate it with 7 records. -- Just copy and past them on psql prompt. DROP TABLE COMPANY; CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'David', 27, 'Texas', 85000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Kim', 22, 'South-Hall', 45000.00 ); INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 );
创建 COMPANY 表,数据内容如下:
nhooodb# select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows)
以下使用了布尔表达式(SALARY=10000)来查询数据:
nhooodb=# SELECT * FROM COMPANY WHERE SALARY = 10000; id | name | age | address | salary ----+-------+-----+----------+-------- 7 | James | 24 | Houston | 10000 (1 row)
数字表达式常用于查询语句中的数学运算:
SELECT numerical_expression as OPERATION_NAME [FROM table_name WHERE CONDITION] ;
numerical_expression 是一个数学运算表达式,示例如下:
nhooodb=# SELECT (17 + 6) AS ADDITION ; addition ---------- 23 (1 row)
此外 PostgreSQL 还内置了一些数学函数,如:
avg() : 返回一个表达式的平均值
sum() : 返回指定字段的总和
count() : 返回查询的记录总数
以下示例查询 COMPANY 表的记录总数:
nhooodb=# SELECT COUNT(*) AS "RECORDS" FROM COMPANY; RECORDS --------- 7 (1 row)
日期表达式返回当前系统的日期和时间,可用于各种数据操作,以下示例查询当前时间:
nhooodb=# SELECT CURRENT_TIMESTAMP; current_timestamp ------------------------------- 2019-06-13 10:49:06.419243+08 (1 row)