Mysql 常用基本语法

--查看当前数据库所有的表
show tables;

--查询表的信息
select * from tablename;

--根据已有的表创建新表
create table table_new like table_old;

--删除表
drop table tablename

--向表中增加字段  test_new 增加的字段名字 varchar(10) 增加字段的类型及长度
alter table tablename  add column test_new varchar(10);

--删除表中的某个字段 test_new 为要删除的字段名
alter table tablename drop column test_new;

--添加主键   primary 主键关键字
alter table tablename add primary key(需要添加主键的字段)

--创建索引 index 索引关键字  goods_new 索引名 name 为需要建立索引的字段 
create index goods_new on tablename(name);

--删除索引 
drop index indexname on  tablename; 

--查看索引
show index from tablename;

--创建视图    as后面接的是语法
create view viewname as select * from tablename

--删除视图 
drop view viewname;

--插入数据
insert into tablename (id,name) values (1,'其他');

--连接查询  连接查询使用 on
select c.name,g.description,g.name,g.no,g.price from goods g
 join category c on g.category_no = c.category_no and c.category_no = '1003';
 
 --子查询  注: 子查询的查询字段只能有一个  不能有 * 出现  否则会报 #1241错误  因为子查询只能返回一个结果集 子查询使用 in(子查询)
 select g.id,g.category_no,g.description,g.name,g.price from goods  g
  where g.category_no in(select c.category_no from category c where c.category_no ='1005' and g.category_no = c.category_no) 


--mysql 没有top newid() 函数  只能使用 limit
--查询从第0条 到第3条数据
select * from category limit 0,3

--查询 id 为1-4之间的数据 
select * from category where id between 1 and 4;

--查询表里面指定数据
select * from category where category_no in('1001','1002','1005')

--按商品编号 分组 查询价格最小值 
--  聚合函数
--  count(字段) 统计函数  
--avg(字段) 求某个字段的平均值  
--min(字段) 最小值  
--max(字段) 最大值 
--sum(字段) 求和
select good_name,min(price) from goods group by good_no;
  --排序  asc 正序   desc 倒序
select * from category c order by c.category_no asc
--注 : order by 是排序  asc 正序 desc 倒序 默认是 asc  
-- order by 执行之后会进行全表扫描,降低性能 ,如果数据量大的时候 要排序的时候尽量按照组合索引中的字段进行 order by 
--  order by 后面可以跟多个字段,优先级按先后顺序

--  group by 是分组  
--  把相同的列放到一组。group by的实现过程除了要使用排序操作外,还要进行分组操作。
--  group by操作想要利用索引,必须满足group by字段必须同时存放于同一个索引中,且该索引是一个有序索引,
--  而且,使用不同的聚合函数也会影响是否使用索引来实现group by操作。
-- group by 后面要搭配聚合函数一起使用,没有在group by后的字段,
-- select的时候必须使用聚合函数(sum,count,max,min)。group by 可以和having一起使用来对数据过滤,
-- having后面也必须是聚合函数。如:select no,count(1) from test group by no having count(1) > 1。

--修改表的名字 rename 关键字
alter table goods_old rename to goods_new;

--去重查询(去除重复数据查询) 关键字 distinct 后面接 需要去除重复的字段 
--注: distinct 关键字必须要在字段前面  否则会报错
select distinct name,category_no,description,no,price from goods;

--group by 也可去重查询 group by 后面接 需要去重复的字段
--使用场景:当数据有唯一主键时 使用description 无法做到去重复查询 当然也可以查询的时候不查询唯一主键这个字段,
--但是有时候我们需要拿这个唯一主键进行业务操作的时候,distinct 关键字显然无法满足,这个时候就可以使用 group by 来进行去重查询
select id,name,no,description,price,category_no from goods group by name;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值