常见关系型数据库SQL增删改查语句

常见关系型数据库SQL增删改查语句:

  1. 创建表(Create Table):

    CREATE TABLE employees (
        id INT PRIMARY KEY,
        name VARCHAR(50),
        age INT,
        department VARCHAR(50)
    );
    ```
    
    
  2. 插入数据(Insert Into):

    INSERT INTO employees (id, name, age, department)
    VALUES (1, 'John Doe', 30, 'IT'),
           (2, 'Jane Smith', 35, 'HR'),
           (3, 'Bob Johnson', 28, 'Sales');
    ```
    
    
  3. 查询数据(Select):

    -- 查询所有员工的姓名和部门
    SELECT name, department
    FROM employees;
    
    -- 查询年龄在30岁以上的员工
    SELECT *
    FROM employees
    WHERE age > 30;
    
    -- 查询销售部门的员工数量
    SELECT COUNT(*)
    FROM employees
    WHERE department = 'Sales';
    ```
    
    
  4. 更新数据(Update):

    -- 将ID为1的员工的年龄更新为32岁
    UPDATE employees
    SET age = 32
    WHERE id = 1;
    ```
    
    
  5. 删除数据(Delete):

    -- 删除年龄小于25岁的员工
    DELETE FROM employees
    WHERE age < 25;
    ```
    
    
  6. 联结(Join):

    -- 查询员工和部门表联结后的结果
    SELECT e.name, d.department_name
    FROM employees e
    INNER JOIN departments d ON e.department_id = d.id;
    ```
    
    
    
    
  7. 子查询(Subquery):

    -- 查询平均年龄大于公司平均年龄的员工
    SELECT name, age
    FROM employees
    WHERE age > (SELECT AVG(age) FROM employees);
    
    -- 查询部门中年龄最大的员工
    SELECT name, age
    FROM employees
    WHERE age = (SELECT MAX(age) FROM employees WHERE department = 'IT');
    ```
    
    
  8. 排序(Order By):

    -- 按年龄升序排序查询员工
    SELECT name, age, department
    FROM employees
    ORDER BY age ASC;
    
    -- 按部门降序、年龄升序排序查询员工
    SELECT name, age, department
    FROM employees
    ORDER BY department DESC, age ASC;
    ```
    
    
  9. 分组(Group By):

    -- 按部门计算每个部门的员工数量
    SELECT department, COUNT(*) as employee_count
    FROM employees
    GROUP BY department;
    
    -- 按部门计算每个部门的平均年龄和最大年龄
    SELECT department, AVG(age) as avg_age, MAX(age) as max_age
    FROM employees
    GROUP BY department;
    ```
    
    

使用子查询、排序和分组的常见SQL操作。可以根据具体需求和数据库结构进行适当调整和修改这些示例。请注意,不同的数据库管理系统可能会有一些语法上的差异,因此在实际使用时,请参考所使用的数据库系统的文档和语法规范。

你可能感兴趣的:(随笔,数据库,sql,oracle)