Oracle 数据库中常用的操作,包括增删改查
、同义词创建
、合并更新
、建表
、建索引
、聚合查询
和多表查询
。通过这些操作,可以有效地管理和查询 Oracle 数据库中的数据,日常工作中也会事半功倍。
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary)
VALUES (1001, 'vincent', 'ding', '[email protected]', TO_DATE('2024-08-18', 'YYYY-MM-DD'), 'IT_PROG', 60000);
UPDATE employees
SET email='[email protected]',salary = salary * 1.10 -- 给所有IT员工加薪 50% ,哈哈哈哈哈
WHERE job_id = 'IT_PROG';
DELETE FROM employees
WHERE employee_id = 1001;
SELECT employee_id, first_name, last_name, salary
FROM employees
WHERE salary > 50000
ORDER BY salary DESC;
CREATE SYNONYM emp_syn FOR employees;
emp_syn
是给 employees 表创建的同义词。emp_syn
来替代 employees 进行查询。MERGE
语句用于根据条件决定是执行 INSERT
还是 UPDATE
操作。MERGE INTO employees e
USING (SELECT 1002 AS employee_id, 'Jane' AS first_name, 'Smith' AS last_name, '[email protected]' AS email, 'IT_PROG' AS job_id FROM dual) src
ON (e.employee_id = src.employee_id)
WHEN MATCHED THEN
UPDATE SET e.first_name = src.first_name, e.last_name = src.last_name, e.email = src.email
WHEN NOT MATCHED THEN
INSERT (employee_id, first_name, last_name, email, hire_date, job_id)
VALUES (src.employee_id, src.first_name, src.last_name, src.email, SYSDATE, src.job_id);
target_table
:目标表 employees e
,数据将被更新或插入到该表中。source_table
:源表 src
,提供要合并的数据。ON
:指定用于匹配的条件。WHEN MATCHED
:当 ON 条件匹配时执行 UPDATE 操作。WHEN NOT MATCHED
:当 ON 条件不匹配时执行 INSERT 操作。CREATE TABLE employees (
employee_id NUMBER(6) PRIMARY KEY,
first_name VARCHAR2(20),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25) UNIQUE,
hire_date DATE DEFAULT SYSDATE,
job_id VARCHAR2(10) NOT NULL,
salary NUMBER(8, 2)
);
datatype
:列的数据类型,如 VARCHAR2
, NUMBER
, DATE
等。DEFAULT expr
:指定列的默认值。constraint
:列级约束,如 NOT NULL
, UNIQUE
, PRIMARY KEY
等。table_constraint
:表级约束,如 PRIMARY KEY
, FOREIGN KEY
, CHECK
等。CREATE INDEX idx_emp_last_name ON employees(last_name);
idx_emp_last_name
是创建在 employees
表 last_name
列上的索引DROP
)DROP INDEX index_name;
SELECT index_name
FROM user_indexes
WHERE table_name = 'TABLE_NAME';
SELECT job_id, COUNT(*) AS employee_count, AVG(salary) AS average_salary
FROM employees
GROUP BY job_id
HAVING AVG(salary) > 50000;
GROUP BY
用于将数据按 job_id 分组。HAVING
子句用于过滤分组后的数据。SELECT e.employee_id, e.first_name, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
SELECT e.employee_id, e.first_name, e.last_name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;
SELECT e.employee_id, e.first_name, e.last_name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;
SELECT e.employee_id, e.first_name, e.last_name, d.department_name
FROM employees e
FULL JOIN departments d ON e.department_id = d.department_id;
SYNONYM
):用于创建数据库对象的别名,简化访问。MERGE
语句:用于基于匹配条件在目标表中进行更新或插入操作。CREATE TABLE
):定义数据库表及其列和约束条件。