MySQL語句設計

表數據插入:

1、insert into 表名 (字段名...)values(’值‘);


擴展:

2、insert into 表名 select*from 表名2;

3、insert into 表名(字段名...)select 對應的字段名... from 表名2 where 條件 limit 10;

4、insert into bbs_user values(null,'xiaohong',123456,13994137211,123,1);值和字段一一對應,一個不能少哦

limit的用法:

limit    10;    表示限制的個數爲10條

limit 10,10;    表示從第10條開始(跳過10,從11開始),限制的個數爲10條(條件,條數)

例子:select*from bbs_user limit 5,5;


分頁:

$page 當前頁碼

$offset 偏移量

$pagesize = 10 每頁顯示數據條數

第一頁

limit 0,10;

第二頁

limit 10,10;

第三頁

limit 20,10;


$offset = ($page-1)*$pagesize;

select * from bbs_user limit $offset , $pagesize;


查詢操作:

查詢所有數據包,含有所有字段

mysql> select*from bbs_user;


查詢username,userpwd 的所有數據

mysql>select username,userpwd from bbs_user;


查詢id=3的數據,數據中只用username和userpwd

mysql>select username,userpwd from bbs_user where id=3;


查詢id>0的數據,數據中包含username,userpwd 總共要查1條

mysql>select username,userpwd from bbs_user where id>0 limit 1;


查詢id>0的數據,從第二條開始取一條,只包含username,userpwd

mysql>select username,userpwd from bbs_user where id>0 limit 1,1;

distinct的用法:

從bbs_user 查詢 username字段的數據,過濾掉重名(只針對一個字段)

mysql>select distinct username from bbs_user;

注意:distinct關鍵字的作用範圍是整個查詢的列表,而不是單獨的一列。在同時對兩列數據進行查詢時,如果使用了DISTINCT關鍵字,將返回這兩列數據的唯一組合。

mysql>select distinct id,username,sex from bbs_user;

as語句的用法

別名:使用as給表或字段可以起個別名,as可以省略

目的:可以讓很長的表名或者字段名變的簡潔,防止表名和字段名重複

在多表關聯查詢的情況下,如果表中有同名的字段,必須使用別名加以區分。

1、分解動作

第一步:select    from    bbs_order as o,  bbs_user as u  where    ...

第二步:select   u.username as uname,  o.username,  o.bianhao  from  bbs_order as o,bbs_user as u where    o.username=u.username;


2、AS可以省略不寫,留一個空格即可

select    u.username uname,o.username,o.bianhao   from   bbs_user o,bbs_user u    where    o.username=u.username; 

多表查詢

Order By的用法:

排序查詢:將查詢到的結果按照指定字段順序排序,如果第一個字段不能排列出順序先後,就會按照後一個字段進行排序

select * from 表名 where 條件 order by 字段1 asc|desc,字段2 asc|desc...;

asc: 從小到大    順序

desc:從大到小    逆序

用法:帖子置頂,置頂爲1,默認爲0


and    &&

or    ||

not


<

>

=

<=

>=

!=

is null

is not null

between 值 and 值

not between 值 and 值

like的用法:模糊查詢

(not)like '% a_i%';下劃線‘_’的作用:代表任意字符

like    '%a';結尾是a

like    'a%';頭部是a


統計:

次數統計

count()count(*)count(字段)


求和:sum();

平均值:avg();

最大值:max();

最小值:min();

版本號:version();


分組:group by

對分組結果再過濾:having

select sum(money) from bbs_user group by username having id>5;


where 字段    in(值1.值2.值3。。。)


子查詢

where username in (select username from 表名 where 條件);

判斷操作是否成功:

1,插入操作

mysql_insert_id()>0

2,刪除操作

mysql_affected_rows()>0

3,修改操作

mysql_affected_rows()>0

4,select 查詢

mysql_num_rows($result)>0






























































發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章