Mysql 常用语句记录
1、查询数量 count(*)
select count(*) as mycount from table后面可以加入限制条件(where或其他)
count(*) 是函数 * 号是指输出所有, * 可以换成条件式 如 (distinct username) mycount 是输出名 table是表名
假设该表有五条数据 输出为 mycount = 5
2、inner join 关键字
select function from table1 t1 inner join table2 t2 on t1.userid = t2.userid
select t1.username from table1 t1 inner join table2 t2 on t1.userid = t2.userid
function 是函数(如count(*))
3、查询函数 select
select * from table 查询整张表
select column from table 查询表中某列
select colunm1, column2 from table 查询表中多列, 之间逗号隔开
4、删除语句 delete
delete from table where userid = 1 删除表中某行
delete from table 删除表中所有行
5、更新语句 update
不加where语句就是把该表的username全改了
update table set username = dasd where userid = 1
修改两个值
update table set username = ‘dasd’,userphoto=‘dsada’ where userid = 1
6、插入语句 insert
insert into table (userid, username) values (1, ‘sdad’)
7、只查询不同数据 distinct
select distinct username from table
高级写法
select count(distinct username) from table
查询表中不同的username的数量
8、where语句
查询userid大于1的数据
select * from where userid > 1
查询userid在从1到6 的数据
select * from where userid between 1 and 6
9、like语句 以某种模式搜索
搜索username以U开头的数据
select * from table where username like ‘U%’
搜索username以u结尾的数据
select * from table where username like ‘%u’
搜索username中包含u的数据(包括头尾)
select * from table where username like ‘%u%’
搜索username中不包含u的数据(包括头尾)
select * from table where username not like ‘%u%’
10、排序 order by
select * from table order by userid
以userid为准顺序排序
select * from table order by userid,username
以userid为首准排序,若有相同的userid, 则以username对相同的userid数据排序
select * from table order by userid desc
以userid为准逆序
select * from table order by userid desc,username asc
以userid为首准逆序排序,若有相同的userid, 则以username对相同的userid数据顺序排序
注:desc 逆序 asc 顺序
11、ifnull 语句
select ifnull(table.userid, 0) as userid form table
在table表中搜索数据(如果userid不为空则输出userid的值,否则输出0)
输出 userid = userid 或者 0
12、 在表中插入列
alter table 表名 add column 列名 属性
alter table user add column userid int(11)
13、插入外键
alter table 从表 add foreign key 键名 references 主表 键名
alter table product add foreign key (cid) references category (cid)
14、 删除列
alter table 表名 drop column 列名
alter table user drop column userid
15、查询数据库中表的数量
select count(*) from information_schema.tables where table_schema=‘tata’
打印数据库中所有表名
select table_name from information_schema.tables where table_schema=‘tata’
16、多表联合查询
// 多表(两表或两表以上)联合查询userid = 1 且 videoid = 85 的单个数据
select * from satin a left join user b on a.userid = b.userid
left join satinvideo c on a.videoid = c.videoid
where a.userid = 1 and a.videoid = 85
17、修改字段属性
alter table 表名 modify column 字段名 修改的属性
alter table test_satin modify column publishTime TIMESTAMP
18、插入字段
alter table 表名 add 字段名 int(11)
alter table test_satin add userid int(11)
19、修改字段名
alter table 表名 change 原字段名 现字段名 属性
alter table user change password pwd varchar(255)
20、删除列
alter table 表名 drop column 列名
alter table user drop column pwd
21、登录时间
u_logintime TIMESTAMP CURRENT_TIMESTAMP,
23、清空表
① truncate user(表名) 清空表 并且重置自增字段 不写log日志 速度快
② delete from user(表名) 清空表 不会重置自增字段 写log日志 速度慢