mysql必知必会 读书笔记

一.show命令:

1.使用命令行(管理员方式)启动mysql服务:net start mysql57        (mysql57为安装时取得名字)

2.登陆本地mysql数据库:mysql -uroot -p

3.显示已有的数据库:show databases;

4.使用某数据库:use users;

5.(先使用4命令)显示某数据库下的表:show tables;

6.显示某表的信息:show  columns from study;

7.更多show命令可使用help命令来查看:help show;

二.select命令:

1.检索student表中的所有列:select * from student;

2.检索student表中特定列(如name和age列):select name,age from student;

3.检索出不同值得列:select distinct teacher_id from class;        

     注意:distinct应用于所有的列,如:   select distinct teacher_id,c_id from class;中distinct应用于 teacher_id和c_id。



4.select语句返回所有匹配的行;可以使用limit子句返回第一行或前几行。

        select * from class limit 2;         返回前两行。

        select * from class limit 2 offset 0;    从第0行开始返回两行。

5.按(teacher_id)默认的升序排序:select * from class order by teacher_id;

6.teacher_id按升序,c_id按降序:select * from class order by teacher_id,c_id desc;

7.使用limit返回c_id最大的记录:select * from class order by c_id desc limit 1;

三.where子句:


1.空值检查: select * from class where c_name is null;  返回c_name为null的行。

2.and操作符给where子句附加条件:select * from class c_id where c_id<=3 and teacher_id<>3;

3.and 比 or的优先级更高:如:select * from class where c_id=1 or c_id=2 and teacher_id=3;

        会先使用c_id=2 and teacher_id=3过滤,然后结果再和c_id=1进行or。

        所以当遇到此类问题时,最好加括号来明确优先级。如:

        select * from class where (c_id=1 or c_id=2) and teacher_id=3;

4.in操作符:in操作符用来指定条件的范围,范围中每个条件都可以进行匹配。in取合法值得有由逗号分隔,全部括在括号中。

    如:select * from class where c_id in (1,2) order by c_id desc;

  使用in操作符的优点:

        1)在长的合法选项清单时,in操作符的语法更清楚;

        2)在使用in时,计算的次序更容易理解(因为使用的操作符更少)

        3)in操作符一般比or操作符执行更快。

        4)in最大的优点是可以包含其他select子句,使得能够更动态的建立where子句。 

5.not操作符:否定他之后所有的任何条件。

如:select * from class where c_id not in (1,2);

注意:mysql支持对in、between和exists子句取反。

四.使用通配符进行过滤

1.百分号(%)通配符:%表示任何字符出现的任意次数。

如:

    select * from class where c_name like 'bj%';    c_name 以bj开头的学生记录。

    select * from class where c_name like '%bj%';   c_name包含bj的学生记录。     

注意:

    1)尾空格可能会干扰通配符匹配,如:在保存词liming时,如果后面有一个或多个空格,则子句where c_name like         '%liming'将不会匹配他们,因为g最后有多余的字符。解决办法:在搜索模式最后附加一个%,即:where c_name like         '%liming%',一个更好的办法使用函数去掉首尾空格。

    2)虽然似乎%通配符可以匹配任何东西,但有一个例外,即null。即使是where c_name like '%'也不能匹配用值null作为名           名字的行。

2.下划线(_)通配符:下划线只能匹配单个字符而不是多个字符。




猜你喜欢

转载自blog.csdn.net/sinat_38301574/article/details/80114327