MySql数据库的sql基础语句以及用法

60 阅读2分钟

创建数据库

create database mysql;(mysql为数据库的名字 自定义)

切换到数据库

use mysql;(mysql为创建数据库时名字 自定义)

创建表

CREATE TABLE attendance;(attendance为表名,表名自定义)

CREATE TABLE attendance
(
  id              int(11)     DEFAULT NULL,
  name            varchar(32) DEFAULT NULL,
  num             varchar(7)  DEFAULT NULL,
  dept            varchar(12) DEFAULT NULL,
  attendance_date date        DEFAULT NULL,
  late            tinyint(4)  DEFAULT NULL,
  early           tinyint(4)  DEFAULT NULL,
  no_sign         int(11)     DEFAULT NULL
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;

表中的id一列为字段,int一列为类型,DEFAULT NULL默认为空。

添加数据作为演示

insert into attendace values (里面填入你所需要添加的数据,顺序要与表字段一样);

正确添加数据如下

INSERT INTO attendance
VALUES (1, '张三', '80001', '教研部', '2021-12-12', 1, 0, 1);

批量添加
INSERT INTO attendance
VALUES (1, '张三', '80001', '教研部', '2021-12-12', 1, 0, 1),
(2, '张三', '80001', '教研部', '2021-12-13', 1, 0, 1),
(3, '张三', '80001', '教研部', '2021-12-14', 1, 0, 0),
(4, '张三', '80001', '教研部', '2021-12-15', 1, 0, 0),
(5, '李四', '80002', '学工部', '2021-12-13', 1, 1, 0),
(6, '李四', '80002', '学工部', '2021-12-14', 0, 0, 0),
(7, '李四', '80002', '学工部', '2021-12-15', 0, 0, 0),
(8, '王五', '80003', '学工部', '2021-12-13', 1, 1, 0),

用sql操作数据库的查、改、删

以下sql语句用表名为 attendance 做演示:

查询attendance表中的数据

-- --查询所有
select * from attendance;

-- --另外一种写法
select id,name,num,dept,attendance_date,late,early,no_sign from attendance;

-- --查询出attendance表中所有员工的部门,不允许有重复结果
select distinct dept from attendance;

-- --查询出attendance表中在【2021-12-13】这一天的所有考勤信息
select * from attendance where attendance_date = '2021-12-13';

-- --查询出attendance表中 【李四】 所有考勤信息
select * from attendance where name = '李四';

修改

-- --修改id为1的用户的名字为程序员,考勤时间改为2022-01-01---
update attendance set name = '程序员',attendance_date='2022-01-01' where id =1;

删除

-- --删除id为1的用户--
delete from attendance where id = 1;

以上只是最基本的一些操作,没难度,后期发布子查询,复杂查询,内连接,左外连接,右外连接,交叉连接,外键等其他只是。