创建数据库表格

drop table if EXISTS stu;
create table if not EXISTS stu(
	id int primary key,   -- 主键约束 
	name varchar(24) not null unique,  -- 非空、唯一约束
	age int,
	sex char(1) default '男', -- 默认约束
	majorId int,
	foreign key (majorId) REFERENCES major(id)
);

-- 修改major表中的主键可以拥有自增长 auto_increment

alter table major change id id int auto_increment;

下面主要是列举一些数据库常用的实例 :
insert
插入数据
-- -- 修改stu表中的主键,自增长

alter table stu modify id int auto_increment;

delect
eg
delete from stu where id = 7 or id = 8 or id = 9;

update
eg:将姓名为翠花的年龄设置为16,生日设置为2001-12-12 12:12:12

 update stu set age = 16 , birthday='2001-12-12 12:12:12' where name='翠花';

select

  • select*加星号即查询所有信息
  • order by 后接属性,表示将表按照此属性进行排序(默认是升序排列)。
  • desc 在排序属性后加desc ,则进行降序排序。
  • limit :后接数字,来表示去所查询字段的前几个;后接数字1,数字2 表示数字1到数字2这一片段


常用函数

  • 公司中工资前5的员工的信息?(关键字limit,desc)
select *
from s_emp
ORDER BY salary desc
LIMIT 5;
  • 查询和42部门员工职位相同的所有员工的姓名?
    第一步:求出42部门员工的职位
select name
from s_dept
where id='42';

第二步:

select p.first_name
from s_emp p,s_dept t
where p.dept_id=t.id and t.name=(select name
from s_dept
where id='42');
  • 哪些员工的工资和本部门的平均工资一致?
    第一步 先求本部门平均工资
select dept_id, avg(salary)
from s_emp
GROUP BY dept_id

第二步

select *
from s_emp p,(select dept_id i, avg(salary)a
from s_emp
GROUP BY dept_id)s
where s.i=p.dept_id and s.a=p.salary

对于数据库的操作,相对繁琐的是select查询语言。

posted on 2020-12-26 16:34  剑舞红颜笑i  阅读(29)  评论(0)    收藏  举报