MySQL常用命令

来源:互联网 发布:苹果系统基于linux 编辑:程序博客网 时间:2024/06/06 00:48

首先登陆
在CMD命令窗口中,输入
mysql -uroot -p 回车;//采用用户名为root的超级用户名,输入密码。一定要回车再输入密码,如此,密码显示为*号,如果直接在-p后输入密码,则密码是明文,别人翻阅记录就可以看到,不安全。

//建立数据库AB
create database AB;

//显示当前存在的数据库
show databases;

//假设AB是一个数据库名。此步调用此数据库。下方对数据库AB进行操作。
use AB;

//显示数据库AB中的表。
show tables;

//创立表stu,包括id(10位int型数据),name(20位varchar型),age(2位tinyint型)
create table stu( id int(10), name varchar(20), age tinyint(2));

//显示stu中的数据
desc stu;

//插入数据元素,可指定元素进行插入
insert into stu( id , name , age, sex) values( 123, “丽水”, 45, 0),(452, “小花”,23 , 0), (134, “小强”, 1);

//显示stu中的所有数据,*代表所有
select * from stu;

//返回所有数据的name,age的信息
select name,age from stu;

//添加约束条件,返回名字叫做丽水的信息
select * from stu where name=”丽水”;

模糊查询,返回姓名中包含“……水……”的信息,不论水的前方后方是什么
select * from stu where name like “%水%”;

//由于定义男生为1,女生为0,返回0,1用户不好辨认
select sex , age from stu;

// if(sex, “男生”, “女生”) 当sex为真,输出“男生”,为假,输出“女生”;但是 if(sex, “男生”, “女生”) 句子太长,表达的意思不清晰
select if(sex, “男生”, “女生”) , age from stu;

//采用别名,此处stusex就是 if(sex, “男生”, “女生”) 的别名,表意清晰
select if(sex, “男生”, “女生”) as stusex, age from stu;

//逻辑运算符
select name , sex from stu where name like “李%” and sex=0;//选择返回姓李的并且是女生的数据, and 逻辑与,类似的还有or 逻辑或

select concat( “姓名: “, name , “性别:” , sex ) as stuinfo from stu;//concat()将多个数据连接成一个整体,返回时出现在同一个表格中

//修改表格
alter table stu add birday date;//增加一个birday的项,类型是date型

update stu set birday = “1989/10/25”;//将所有birday设置为1989/10/25

update stu set birday = “1989/10/25” where sex=1;//将男生的生日升职为1989/10/25

//限制返回数据数量
select * from stu limit 2;//返回两个

select * from stu order by age asc limit 1;//按照年龄排序,返回前两个,asc代表升序, desc代表降序

//查找年龄最大的
select * from stu order by age asc limit 1;

select * from stu order by age asc limit 0,2;//返回按年龄排序的,从第一个开始,输出2个数据;注意:数据库中数据从0开始。

select * from stu where birday <= “1998/10/21”;//返回生日比 1998/10/21小的数据

//采用子查询生成子表,得到查询依据,再进行主查询
select * from stu where birday <= ( select * from stu order by birday asc limit 1,1 );//此处首先查询按照生日排第二的人的数据,然后输出比这个小的人的数据。解决了当有人生日同样的时候,输出数据不完整的情况。

//按照年查询数据
select year(birday) from stu;//year是date型数据中的一个分量,此时的输出存在重复项,即有几人同样的年份,会输出几次

select distinct year(birday) from stu;//distinct命令只会输出不同的数据,去除重复项

//删除表或者数据库
drop table stu;
drop database AB;

//退出MySQL
quit;
或者
exit;

select version();//显示版本信息
set @s=2;//
select @s*2;//

select

0 0
原创粉丝点击