Mysql查詢例子

2021-06-20 04:19:05 字數 1377 閱讀 9073

近兩天在看「mysql技術內幕」,裡面有些不錯的例子,我想僅看一下是不夠的,動手寫一寫會加深理解。

1,序號問題

比如有這樣乙個表:

+-----+

| a   |

+-----+

|   1 |

|   2 |

|   3 |

| 100 |

| 101 |

| 103 |

| 104 |

| 105 |

+-----+

要求給其新增乙個序號列。

sql語句可以這樣寫:

mysql> select a,@a:=@a+1 num from nianxu,(select @a:=0) as b;

+-----+-----+

| a   | num |

+-----+-----+

|   1 |   1 |

|   2 |   2 |

|   3 |   3 |

| 100 |   4 |

| 101 |   5 |

| 103 |   6 |

| 104 |   7 |

| 105 |   8 |

+-----+-----+

8 rows in set

還有另一種寫法也行:

select a,(select count(*) from nianxu as table1 where table1.a<=table2.a) as num from nianxu as table2;

2,在第1個問題的基礎上(表不變)找出連續的範圍,像這樣:

start        end

1   3

100101

103105

也就是找出各個連續段的最小值與最大值

sql語句可以這樣寫:

select min(a) as start,max(a) as end from

(select a,num,a-num as diff from

(select a,@a:=@a+1 as num from nianxu,(select @a:=0) as a)

as b

) as c

group by diff;

最後結果是:

+-------+-----+

| start | end |

+-------+-----+

|     1 |   3      |

|   100 | 101 |

|   103 | 105 |

+-------+-----+

3 rows in set

上面的sql語句可以先看裡層後看外層。

先寫這幾個吧,以後再加幾個。

mysql子查詢例子

子表查詢 create table stus id int not null auto increment name varchar 10 age tinyint c id int height int primary key id insert into stus values default,x...

mysql多表查詢例子

現在有三個表 角色表 shop role id role name 許可權表 shop privilege id pri name 角色許可權表 shop role pri role id pri id 要查詢角色所擁有的許可權名稱。思路 先查詢角色擁有的許可權 id 在角色許可權表 再通過許可權 ...

MySql幾個查詢更新例子

一 建立乙個表 create table flower id int 11 not null auto increment,color varchar 255 default null,primary key id engine innodb auto increment 6 default cha...