数据库系统原理之SQL(四)

2023-06-25,,

数据库系统原理SQL(四)


1. 数据更新

插入数据

    INSERT…VALUES语句

    #插入多条数据
    insert [into] table_name (column_name,...) values ({expr | DEFAULT},...),{....}
    expr:可以是常量、变量、表达式、也可以是null
    DEFAULT:该列的默认值

    INSERT…SET语句

    #插入一条数据
    insert [into] table_name set column_name="张三",column_age=12

    INSERT…SELECT语句

    #插入子查询出的数据,子查询的字段数量数据类型要和插入表的字段一致
    insert [into] table_name [(column_name,...)] select

删除数据

DELETE FROM table_name [WHERE where_condition] [ORDER BY …] [LIMIT row_count]

修改数据

#修改数据,字段=值,条件,
UPDATE table_name SET column_name={expr1|DEFAULT} [,col_name2={expr2|DEFAULT}]
[WHERE where_condition] [ORDER BY …] [LIMIT row_count]

查询数据

    SELECT 语句

    SELECT [ ALL | DISTINCT | DISTINCTROW ]
    select_expr[,expr...] -- 需要查询的字段
    FROM table_name -- 查询的表,数据来源
    [where where_condition] -- 查询条件
    [GROUP BY {column_name | expr | position } -- 对查询的数据分组,
    [ASC|DeSC],...[WITH ROLLUP]]
    [HAVING where_condition] -- 指定组的选择条件
    [ORDER BY {column_name | expr | position } -- 对查询的结果进行排序
    [ASC | DESC ]...]
    [LIMIT {[offset row_count | row_count OFFSET offset }] -- 限制行数

    别名

    用select查询的时候可以为查询的字段设置别名,如:

    SELECT class_name as name from class

    查询班级名称并为字段class_name设置别名name

    可以为表设置别名,如:

    SELECT * FROM t_class as class where class.name="张三"

    查询班级里面名字是张三的人,from的时候设置t_class的别名是class ,后面就可以直接使用别名

    替换查询结果集中的数据

    查询班级中同学的信息,并且把0代表女,1代表男,直接输出中文

    SELECT id,name,age,
    case
    where sex=0 then "女" -- 如果sex是1,则输出女
    where sex=1 then "男" -- 如果sex是0,则输出男
    else "未确定" --否正输出未确定
    end [as] "性别" -- 设置别名为性别
    from class

    交叉连接,又称笛卡尔积

    select * from table_1 [CROSS JOIN] table_2

    内连接,inner join ....on

    -- 需要inner join连接用on连接两张表的外键,以形成连接关系
    select * from table_1 inner join table_2 on table_1.A=table_2.A

    外连接——左外连接(以左边表为基表)left join

    select * from table_1  left join table_2 on table_1.A=table_2.A

    外连接——右外连接(以右边表为基表)right join

    select * from table_1  right join table_2 on table_1.A=table_2.A

    where子句条件查询

    between,把查询范围确定在某个范围内

    -- 查询年龄在18到20之间的学生
    select * from students where age between 18 and 20

    in,列出所有指定条件的值

    -- 查询年龄是18,19,20的学生
    select * from students where age in (18,19,20);
    -- 查询任意所选课程成绩高于80分的学生的学号和姓名信息
    SELECT studentNo,studentName
    FROM tb_student
    WHERE studentNo IN(SELECT studentNo FROM tb_score WHERE score›80);

    Group By 子句

    select * from students group by class

    HAVING子句(过滤分组)查询班级人数大于60的学生

    select * from students group by class having count(*) >= 60

    order by子句,排序。ASC升序,DESC降序

    SELECT * FROM students ORDER BY age DESC,score DESC;

    limit 子句,从第6个同学查询出10个同学

    select * from students limit 5,10

数据库系统原理之SQL(四)的相关教程结束。

《数据库系统原理之SQL(四).doc》

下载本文的Word格式文档,以方便收藏与打印。