SQL 表达式是组合一个或多个值、操作员(/community/tutorials/sql-operators)和 SQL 函数的组合,从而产生一个值。
SQL 表达式
SQL expression can be classified into following categories.
数字 2 数字 3 日期
让我们用样本程序来详细了解表达的类型。
SQL Boolean 表达式
SQL Boolean 表达式基于作为 SQL 查询的一部分提到的条件获取数据. 它在执行查询时只应获取单个值。
1SELECT column
2FROM table_name
3WHERE SINGLE_VALUE_MATCHING_EXPRESSION;
让我们试着用一些数据的样本表来理解布尔式表达式。
──」
EmpId | EmpName | EmpAge | EmpSalary |
---|---|---|---|
1 | John | 32 | 2000 |
2 | Smith | 25 | 2500 |
3 | Henry | 29 | 3000 |
我们将以上面提到的员工表作为例子来考虑。
1SELECT EmpName FROM Employee WHERE EmpId = 1;
上面的查询将产生单个值,这为我们的查询约翰
。 SQL Boolean 表达式应与主键一起使用,以使您始终只得到一个结果。
1select posts.title, posts.author_id from posts, authors
2where posts.author_id = authors.id and
3posts.author_id = (select id from authors where name = 'Pankaj');
上面的查询将返回所有帖子的名称和ID,作者名称为 Pankaj. 在这里嵌入的 SQL 查询应该总是返回只有一行,否则你会收到错误消息,因为提问返回超过1行
。
SQL 数字表达式
SQL 数值表达式用于在 SQL 查询中执行数学操作,其语法如下:
1SELECT NUMERICAL_EXPRESSION as OPERATION_NAME
2FROM table_name
NUMERICAL_EXPRESSION 是 SQL 查询中使用的函数的数学公式。
1SELECT count(*) FROM Employee; -- 3
上面的查询将结果为 3,因为COUNT()函数将根据 WHERE 条款中的条件提供行总数。例如,从 empsalary > 2400 的员工中选择 count() 将返回 2. 还有其他函数,如 sum(), avg(), min(), max() 等。
1SELECT sum(EmpSalary) as "Salary" FROM Employee; -- 7500
2select min(EmpSalary) from Employee; -- 2000
3select max(EmpSalary) from Employee; -- 3000
4select sum(EmpSalary) from Employee; -- 7500
5select avg(EmpSalary) from Employee; -- 2500.0000
SQL日期表达式
SQL Date Expression 结果为 datetime 值. 让我们尝试用一些 sql 语句来理解 Date 表达式。
1SELECT CURRENT_TIMESTAMP; -- 2018-01-20 10:32:37
2
3-- For MYQSL
4SELECT now(); -- 2018-01-20 10:32:57
5
6-- For SQL Server
7SELECT GetDate();
8
9-- For Oracle DB
10select sysdate from Dual; -- 20-JAN-18
上述查询将导致系统的当前时间。 请注意,每个关系数据库供应商都有特定方法来获取当前日期和时刻标记值,所以在一个数据库中的一个函数在另一个数据库中不起作用的可能性很小。