本文摘抄自Oracle官方手册,操作 HR 数据库的例子。
Unlock HR User
Oracle 数据库在安装时会建立一个数据库实例和用户,名为 HR,官方文档通过这个数据库介绍了一些基本操作。默认情况下 HR 账户被禁用,首先需要通过 system 用户解锁 HR 账户。
ALTER USER HR ACCOUNT UNLOCK IDENTIFIED BY orcl123;
执行后,HR 用户的密码就是 'orcl123' 了,数据库返回:
User altered.
随后可以使用 SQL Plus 登陆 HR 账户。
查看Schema Objects
登陆后,可以执行 SQL 查看该 schema 中存储的所有对象。(上一篇中提到的几大对象)
SELECT OBJECT_NAME, OBJECT_TYPE
FROM USER_OBJECTS
ORDER BY OBJECT_TYPE, OBJECT_NAME;
查看schema对象
此表应该是一个静态记录,记录了该 schema 中所有对象的信息。执行这个语句,将看到 34 个结果。官方例子中有索引、过程、序列、表、触发器和视图。
查看表的属性和数据
使用 DESCRIBE 关键词查询表的属性,使用 SELECT 关键词查询表中的数据。查看表的其他信息,可以查看 static data dictionary (应该是数据库中的一些静态记录)。
此处注意的是,查看属性,是命令,不是SQL;查询数据,是 SQL 语句。
查询 employees 表数据
About Queries
查询语句,官方文档中关于 SELECT 关键词的介绍。(我直接摘抄了,中英文切换输入太麻烦了)
SELECT select_list FROM source_list;
select_list specifies the columns from which the data is to be selected, and the source_list specifies the tables or views that have these columns.
A query nested within another SQL statement is called a subquery.
Displaying Selected Columns Under New Headings
When query results are displayed, the default column heading is the column name. To display a column under a new heading, specify the new heading (alias) immediately after the name of the column. The alias renames the column for the duration of the query, but does not change its name in the database.
SELECT FIRST_NAME First, LAST_NAME Last, DEPARTMENT_ID DepId
From EMPLOYEES;
指定列的名字
If you enclose column aliases in double quotation marks, case is preserved, and the aliases can include spaces
SELECT FIRST_NAME "Given Name", LAST_NAME "Family Name"
FROM EMPLOYEES;
用双引号标记,会保留格式
Selecting Data that Satisfies Specified Conditions
呃,这块主要是说了 WHERE 关键字的用法。
SELECT FIRST_NAME, LAST_NAME, DEPARTMENT_ID
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 90;
Where 关键字查询
To select data only for employees in departments 100, 110, and 120, use this WHERE
clause:
SELECT FIRST_NAME, LAST_NAME, DEPARTMENT_ID
FROM EMPLOYEES
WHERE DEPARTMENT_ID IN (100, 110, 120);
指定多个值 where
Other Conditions
还有 AND 和 ORDER 的用法,不贴了,基本上都会SQL了。
ORDER 关键词根据字段排序的时候,只要是 Table 里的 Column 都可以排序,不一定非要是 SELECT 中的 column
Select Data From Multiple Tables
Suppose that you want to select the FIRST_NAME, LAST_NAME, and DEPARTMENT_NAME of every employee. FIRST_NAME and LAST_NAME are in the EMPLOYEES table, and DEPARTMENT_NAME is in the DEPARTMENTS table. Both tables have DEPARTMENT_ID. Such a query is called a join.
SELECT EMPLOYEES.FIRST_NAME "First",
EMPLOYEES.LAST_NAME "Last",
DEPARTMENTS.DEPARTMENT_NAME "Dept. Name"
FROM EMPLOYEES, DEPARTMENTS
WHERE EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
ORDER BY DEPARTMENTS.DEPARTMENT_NAME, EMPLOYEES.LAST_NAME;
JOIN 查询
当然了,表名也是可以在后面添加别名的,在 SELECT 后面使用很方便。
SELECT e.FIRST_NAME "First",
e.LAST_NAME "Last",
d.DEPARTMENT_NAME "Dept. Name"
FROM EMPLOYEES e, DEPARTMENTS d
WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID
ORDER BY d.DEPARTMENT_NAME, e.LAST_NAME;
引用 Table alias
下一节是复杂点的 Operators and Functions in Queries.
网友评论