mysql数据检索和输出_MySql必知必会实战练习(二)数据检索

在上篇博客

1. Select子句使用顺序

select--->DISTINCT--->from--->where--->GROUP BY--->HAVING--->ORDER BY--->LIMIT

(1)DISTINCT

select verd_id from products;

856d44213c831cd6f29f8ba1b67aeffc.png

使用DISTINCT检索出不同值的列表

select DISTINCT verd_id from products;

127bfef384fb6d11118c7fdca7bf0286.png

(2)Group By

首先看下下面3个查询语句的结果:

select count(*) from products;

select * from products where verd_id = 1003;

select count(*) from products where verd_id = 1003;

(1)

277dc1ef1ad27eca54b08154c03110e2.png(2)

b22874654e42e61017283c3b588a99b3.png (3)

6db2baafcc4af49816ceb9cf3ff231ce.png

(1)表示products表的总项数14

(2)列出了verd_id为1003的所有项

(3)显示verd_id为1003的总项数7

再看下面语句的输出结果:

select verd_id, count(*) as num_prods from products GROUP BY verd_id;

2b1f1616b548c025e5094f9df8417215.png

结果一目了然,分别对verd_id进行分组,并显示各组的总项数。

注:如果再select中使用表达式,则必须再GROUP BY字句中指定相同的表达式,不能使用别名。

(3)HAVING

HAVING语句主要是对分组语句进行过滤,WHERE过滤指定的是行而不是分组,事实上,WHERE没有分组的概念

HAVING与WHERE的唯一差别就是WHERE过滤行,HAVING过滤分组

select verd_id, count(*) as num_prods from products GROUP BY verd_id HAVING count(*)>2;

e5d8b25186062551aae51839f44db58a.png

select verd_id, count(*) as num_prods from products GROUP BY verd_id HAVING verd_id = 1003;

563cff8e1456f8ba16a93551c114fb50.png

(4)ORDER BY

select cust_name,cust_address,cust_zip from customers;

fe3ba9baefdca82327fd42754fe2cd92.png

对cust_zip排序

select cust_name,cust_address,cust_zip from customers ORDER BY cust_zip;

89116ffd51c6f1c13fe34737eea4b04c.png

对多列进行排序

select cust_name,cust_address,cust_zip from customers ORDER BY cust_address,cust_zip;

366812244c6e09d4a74ff431957cc90a.png

指定排序方向:默认升序(ASC),为了进行降序排序,必须指定DESC关键字

select cust_name,cust_address,cust_zip from customers ORDER BY cust_zip DESC;

a23bd52fd9cb447cdabafbfa4e174497.png

(5)LIMIT

LIMIT关键子对输出的行数限制,指定其实行和行数

select cust_name,cust_address,cust_zip from customers ORDER BY cust_zip DESC LIMIT 2,4;

d3ee2d864fa2f15fbbaea8181946b945.png

(6)综合使用

select verd_id, count(*) as num_prods from products GROUP BY verd_id HAVING count(*) > 0 ORDER BY verd_id DESC LIMIT 1,3;

2daa567d57e2de59e461d5e14a15f2ab.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值