数据库常用结构化sql语句_3

10、limit 限制查询结果条数

   在mysql数据库里面我们要想显示前10行,或者第x行到n行之类的格式显示,这时limit将是我们最好的选择。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

select  from  user limit 5; #显示前5行

1    kailinux    javadocker

2    LInuxmysql    NULL

3    python    NULL

4    LInux    redis

5    linux    0

假如我们想看倒数3行,但是limit不支持倒序,我们可以用以前的方式实现

select   from  user limit 21,3;

26    redispyhon    

27    PYthon234    

28    winner1234    

从3开始显示5条

select   from  user limit 3,5;

4    LInux    redis

5    linux    0

6    redis    name 

7    kailinux    javadocker

8    LInux    redis

11、mysql 常用函数

 连接函数concat()

语法:CONCAT(str1,str2,...) 可以用来拼接查询结果,

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

select   CONCAT(username,'*****',passwordfrom user  #将user表的username和password列用4

个****拼接。

结果:

kailinux*****javadocker

LInuxmysql*****NULL

python*****NULL

LInux*****redis

linux*****0

用下划线或者横线拼接

kailinux_javadocker

LInuxmysql_NULL

python_NULL

LInux_redis

kailinux-javadocker

LInuxmysql-NULL

python-NULL

select   CONCAT(username,'',passwordfrom user #不指定间隔直接拼接两列

kailinuxjavadocker

LInuxmysqlNULL

pythonNULL

LInuxredis

 由此可以看出concat()函数在拼接的时候可以指定任意连接符,达到对数据查询不同结果的显示。

随机函数rand()

  这种随机函数,可以在查询结果里面随机排序之类的处理

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

select   *  from user  order by rand();

5    linux    0

8    LInux    redis

15    python    javadocker

16    LInux    

2    LInuxmysql    NULL

7    kailinux    javadocker

28    winner1234    

20    centos    

17    linux    999

6    redis    name 

3    python    NULL

26    redispyhon    

22    rediswinner    

25    PYTHoREDIS    

27    PYthon234    

这种随机数里面就可以用来抽奖之类的,我们将随机排序的再获取3行,

select   *  from user  order by rand() limit 3;

23    PYthonmysql    

27    PYthon234    

4    LInux    redis

统计列数count()

select count(*)  from user   就可以查询出某表里面包含多少条数据等,这里挑选列时一般选择主键相关的列。

1

2

3

4

select   count(*)  from user  ;

24

select count(id ) from user  ;  但是这种在数据量大时会比较慢

求和函数sum()

1

2

3

select   sum(id)  from user  ; #对id求和

356

求最大值max()

1

2

select   max(id)  from user  ;

28

求最小值函数()

1

2

select   min(id)  from user  ;

1

平均函数avg()

1

2

select   avg(id)  from user  ;

14.8333

分组函数group  by

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

select   username,count(*) from user  GROUP BY username ; #按用户名分组,可以统计

出相同用户的信息

centos    1

kailinux    3

LInux    5

LInuxmysql    1

python    2

PYthon234    1

PYTHonmysql    2

PYTHoREDIS    1

redis    3

redispyhon    1

rediswinner    1

ubuntu    1

winner1234    1

winnerredis    1

猜你喜欢

转载自blog.csdn.net/choupiaoyi2794/article/details/81185878