查询数据表中的数据

基本查询方法

实例1:多字段查询

select 字段1,字段2……字段n from user;

解析:从user表中查询字段1、字段2一直到字段n的记录,且展示顺序也是这样。

实例2:as新命名查询

select 字段1  as 'newname' from user;

解析:在user表中,查询到字段1中记录的数据,并将字段1改名为newname展现出来。但是,并不能修改数据库中的字段名,而且这个引号不能省略。

distinct不重复查询方法

实例1:

select distinct  email from user;

解析:将user表中email这一列的数据,只显示不重复的数据。在email这里,不建议用多个列,因为distinct最好单独用在一个列上。

逻辑组合语句查询方法:

实例1:and并且

select id from user where pwd=md5(123456) and email='[email protected]';

解析:查询user表中密码为md5(123456)加密过的,且邮箱地址为'[email protected]'的id号码。

实例2:运算符

select id from user where pwd=md5(123456) and id >=5;

解析:查询密码为md5(123456)加密过的且id大于等于5的ID号码

同理,and可以变成or,就是或,其他的例如!=不等于,各种运算符,都可以尝试。

实例3:is not 不为……

select id from user where pwd is not null;

解析:查询user表中,密码不为空的ID号码。

同理,若改成is则是为空的……

实例4:between ……and……在……和……之间

select * from user where id between 6 and 8;

解析:查询user表中,id在6和8之间的所有符合条件的id号码。

同理,也可以not between,那么就查询不在6和8之间的id号了

实例5:模糊查询like

select * from user where username like '%user%';

解析:查询user表中,username字段中,中间有user字符的所有记录。%表示可以为任意数值。

同理,not like就是查询与上方相反的数据。

实例6:in指定范围查询

select * from user where id in(5,7,8);

解析:查询id在5,7,8三个数字中的所有记录。

实例7:order排序

select * from user order by score ASC;

解析:查询user表中所有的以分数为关键字,由低向高排序的记录;ASC代表由低向高排序。

select * from user where order by score DESC;

解析:同上,只不过是按分数由高到低排序,查询。若不添加DESC之类的,就会默认从低向高排序。

计算表中记录的方法

实例1:count计算id数量

select count(id) num from user where id>6;

解析:计算user表中,符合where条件的id数量,展现出来,并且起名为num;

实例2:avg计算平局值

select avg(score) num from user;

解析:将user表中score字段中所有记录的平均值计算出来,并且以num的名字展现。

实例3:min最小值max最大值

select min(score) minname from user;

select max(score) maxname from user;

解析:查询score字段中的最小值和最大值,并且以相应的名字展现

实例4:综合实例sum和group

select userid,sum(score) as total from mark group by (userid);

解析:查询mark表中以userid为分组标准的userid字段和分数字段的总和,userid字段值相同的为一组。

实例5:综合实例count和total

select userid,count(id) as num from mark group by(userid);

解析:在以userid值为标准分组后,计算出每一组的id值是多少,以num的名字展现。这里我用的是userid代表用户名字,id表示考试的科目,只要count计算出来的科目总数符合要求,那么就说明用户没有缺考。

实例6:综合实例min和group

select userid,min(score) as minname from mark group by(userid);

解析:查询userid的最低分数并且展现。。。。

select userid,xk,min(score) as minname from mark group by(userid);

解析:这就是在上面的基础上,又展现出了到底哪门学科是最低分。

select userid,xk,min(score) as minname from mark group by(userid) having min<70;

解析:后面新多出来的having是指在前面的基础上,再次筛选,筛选条件是min<70的。附一句:having只能跟在gruop by后面进行二次筛选。

你可能感兴趣的:(查询数据表中的数据)