1、在终端查:
mysql --version;
2、登陆mysql以后查询:
select version();
登陆mysql的命令:
mysql -p;接下来输入登陆密码即可。
查看数据库:
show databases;
使用某一个数据库:
use 数据库名;
查看数据表:
show tables;
创建数据库:(数据库名称区分大小写)
create database 表名;
创建数据表:
create table pet (name varchar(20),owner varchar(20), species varchar(20),sex char(2),birth DATE,death DATE);
查看表结构:
describe 表名;
插入数据:
insert into pet values('Puffball','Danie','hamster','f','1999-03-30',null);
select * from pet;
修改数据:
update pet set death='1998-02-20' where name='Buff';
选择特殊行:
select * from pet where sex='f';
AND 和OR可以混用,但是AND比OR具有更高的优先级。如果使用两个操作符,使用圆括号致命如何对条件进行分组。
select * from pet where (species='snake' AND sex='m') OR (species='dog' AND sex='f');
选择特殊列:
select name,birth from pet;
减少输出到最少,增加关键字检索出每个唯一的输出记录:
select distinct name,birth from pet;
为结果排序使用关键字ORDER BY ,默认是升序,添加DESC(表示倒序)
select name,birth from pet order by birth;
使用Mysql提供的函数计算日期,例如计算年龄或提取日期部分。
select name,birth,curdate(),(year(curdate())-year(birth))-(rigth(curdate(),5)<right(birth,5)) as age from pet;
year()提取日期的年部分,right()提取日期的MM-DD部门的最右边5个字符,比较MM-DD值的表达式部分的值一般为1或者0。
找出下个月生日的动物名单,使用date_add()函数
select name,birth from pet where month(birth)=month(date_add(curdate(),interval 1 month));
NULL值操作,NULL意味着“没有值”或“未知值”,在MYSQL中0意味着假,而其他值意味着真。
在group by 中,两个NULL值视为相同。
执行order by时,如果运行ORDER BY ... ASC,则NULL值出现在最前面,若运行ORDER BY ... DESC ,则NULL出现在最后面。
可以在定义为NOT NULL的列内插入0或者空字符,实际是NOT NULL。
MYSQL模式匹配允许使用"_"匹配任意单个字符,而“%”匹配任意数目字符(包括零字符)。在mysql中,sql模式默认是忽略大小写的,不能使用”=“或“!=”而应该使用LIKE或NOT LIKE比较操作符。
找到以"b"开头的名字:
select * from pet where name like "b%";
找到以“fy”结尾的名字:
select * from pet where name like '%fy';
找到名字中含有“w”的名字:
select * from pet where name like '%w%';
找到长度为5个字符的名字:
select * from pet where name like "_____";
由MYSQL提供的模式匹配的其他类型是使用扩展正则表达式。当对这类模式进行测试时,使用REGEXP和NOT REGEXP操作符(或RLIKE和NOT RLIKE,他们是同义词)。
"."匹配任何单个的字符。
“[...]”匹配在方括号内的任何字符。如[0-9]匹配任何数字。
"*"匹配零个或多个在他前面的字符。如“X*”匹配任何数量的“X”字符,"[0-9]*"匹配任何数量的数字,而“.*”匹配任何数量的任何字符。
如果REGEXP模式与被测试值的任何地方匹配,模式就匹配(这不同于LIKE模式匹配,只有于整个值匹配,模式才会匹配)。
为了定位一个模式以便它必须匹配被测试值的开始或结尾,在模式开始处使用“^”或者在模式的结尾用“$”。
找到以“b”开头的名字:
select * from pet where name regexp '^b';
找到以”fy“结尾的名字:
select * from pet where name regexp 'fy$';
找到名字中含有“w”的名字:
select * from pet where name regexp 'w';
找到长度为5个字符的名字:
select * from pet where name regexp '^.....$';
select * from pet where name regexp '^.{5}$';
select count(*) from pet;
使用一个以上的表进行操作,注意事项:
select p1.name,p1.sex,p1.species ,p2.name,p2.sex,p2.species from pet as p1 ,pet as p2 where p1.species=p2.species and p1.sex='f' and p2.sex='m';
select database();
select article,dealer,price from shop where price =(select max(price) from shop);
或者按照价格降序排列所有行并用mysql特定的limit子句只得到第一行。
select article,dealer,price from shop order by price desc limit 1;
使用用户变量:
select @min_price:=min(price) ,@max_price:=max(price) from shop ;
select * from shop where price=@min_price or price=@max_price;