SQL支持三种类型的注释 如下
注释 --注释 /* 这就是注释我的三个方式 */
/* 数据库的相关操作*/
数据库的创建和使用
create database database_name;
use database_name;
删除数据库
drop database [ if exists ] database_name; -- 使用这个命令要异常小心
创建表
create table table_name (
id int not null auto_increment,
col1 int not null default 1,
col2 varchar(45) null,
col3 date null,
primary key("id"));-- 设置主键
/* 修改表的相关操作*/
添加列
alter table table_name add col char(20);
删除列
alter table table_name drop column col;
删除表
drop table table_name;
*/
/* 插入的相关操作 */
普通的插入操作很简单的
insert into table_name(col1,col2) values(value1,value2);
插入检索的数据--复制已存在的表数据到新表--
insert into table_name(col1,col2) select col1,col2 from table_name2;
将一个表的内容插入到一个新表;
create table mytable_name2 as select * from table_name;
更新
update mytable set col = val where id = 1;
删除
delete from mytable where id =1;
truncate table mytable;# 清空表(删除表的所有行)
关注: 使用update和delete时一定要使用where子句,不然会破坏整张表数据,可以用select 先测试,防止错误删除
查询 distinct 去重
select distinct col1,col2 from mytable;
limit 限制返回值的数量
select * from mytable limit 5; -- 第一个参数是起始行,第二个参数是要返回的行数
select * from mytable limit 1,3; -- 从第一行开始,共返回三条数据 返回3~5行;
排序 asc (默认)升序 desc降序 可以按多个列进行排序,并且为每个列指定不同的排序方式:
select * from mytable order by col1 desc,col2 asc;
过滤
select * from mytable where col is null ;
/* <> != 不等于
!> 小于等于 <=
!< 大于等于 >=
between 在两个值之间
is null 为空
优先处理 and 然后处理 or 可以使用括号来确定优先级
in 操作一组值
*/
通配符
/* % >=0 个字符 — 1 个任意文档
- [] 匹配括号内的内容 ^ 表否定
*/
select * from mytable where col like '[^AB]%'; -- 不以A和B开头的任意文本
计算字段
-- AS 用来取别名
select col1 * col2 as col from mytable;
concat 连接两个字段,trim 去除首尾空格
select concat(trim(col1),'(',trim(col2),')') as concat_col from mytable;
分组
SELECT col, COUNT(*) AS num FROM mytable GROUP BY col ORDER BY num; -- GROUP by 在where 之后 排序之前;
子查询
select * from mytable1 where col1 in (select col2 from mytable2);
网友评论