mysql 数据库中经常使用的sql语句

这个颇有必要记录保存下来,方便你我。。如下为普通建表为例,而后进行SQL操做。


表结构:
  1. CREATE TABLE  `test` (                           //表名  
  2. `u_id` INT( 10 ) NOT NULL AUTO_INCREMENT ,      //id号,自动增加  
  3. `u_name` VARCHAR( 10 ) NOT NULL ,              //姓名  
  4. `regdate` DATE NOT NULL ,                      //日期  
  5. `remark` VARCHAR( 10 ) NOT NULL ,             //备注,职称  
  6. PRIMARY KEY (  `u_id` )                      //设置id号为主键  
  7. ) CHARACTER SET = utf8;                    //设置编码 utf8
一: insert  添加数据
  1. INSERT INTO  `test` (  `u_id` ,  `u_name` ,  `regdate` ,  `remark` )  
  2. VALUES (  
  3. '1',  '浩子',  '2011-04-01',  'voip'  
  4. );   //插入单条数据
  1. insert into test (u_id,u_name,regdate,remark) values (null,"孙悟空",now(),"弼马温") // 这里u_id 为自动增加,因此能够写空,now()是一个插入获取本月的日期函数[font=arial] [/font]
  1. insert into test (u_id,u_name,regdate,remark) values  
  2. (null,"孙悟空",now(),"弼马温"),(null,"鸟人",now(),"会飞"); //插入多条数据
二:update  修改语句
  1. update test set u_name="小浩子" where u_id=1  //这里是修改了u_name 的值的,后面带上了u_id 的值,否则后会把整个数据所有修改,必定要谨慎
三: datele 删除语句
  1. delete from test where u_id=4  //删除u_id 为4的这行记录
四:select 查询语句  (这个很重要,大多数操做都是围绕查询来作的)
  
  1. select * from test  #查询表中所有数据  
  2. select * from voip.test #查询所有还能够这么写,voip表示为数据库名  
  3. select u_id,u_name from test  #查询表中某一个或多个字段的数据值  
  4. select u_name as name from test  #查询出结果字段以别的名称显示,但真实的字段结构不会变  
  5. select * from test where u_name="浩子"  #查询u_name 字段等于浩子的全部数据  
  6. select * from test where u_name <> "浩子" #查询u_name 字段不等于浩子的全部值  
  7. select * from test where u_id in (1,2,5)  #查询u_id 字段中包含1,2,5的数据  
  8. select * from test where u_id not in (1,2,5) # 查询u_id 字段中不包含1,2,5 的数据  
  9. select * from test where u_name like "%浩%"   #查询u_name 字段中 匹配或包含有“浩”的数据  
  10. select * from test where u_id between 1 and 5  #查询u_id 字段中 第1条到第5条的数据  
  11. select * from test where u_id not between 1 and 5  #查询u_id 字段中 不是第1条到第5条的数据  
  12. select * from test where u_id >=1 #查询u_id字段中大于而且等于1的数据, 反之则是 <= 、>、< 均可以  
  13. select * from test where u_name="浩子" and remark="voip"  # 查询u_name的值等于“浩子”而且 remark=“voip” 的共同条件  
  14. select * from test where u_name="浩子" and remark="voip"  # 查询查询u_name的值等于“浩子” 或者 remark=“voip” 中的某一条件  
  15.   
  16. select * from test group by remark  #查询remark字段中不一样的统称,打个比分说该字段中有学生N个,工人N个,那么查询出来的结果就学生和工人,而不会显示更多的学生和工人  
  17. select * from test order by regdate asc  #查询regdate(日期)字段中正序排列,也就是说按最先日期排列  
  18. select * from test order by regdate desc #查询regdate(日期)字段中倒序排列,也就是说按最晚日期排列,一般应用在最新发表什么什么的排序  
  19. select * from test limit 0,3  # 查询表中前3条记录(下表从0开始) select * from test limit 3 这样写也OK  
  20.   
  21. select count(*) from test #统计表中共有多少条记录 select count(u_id) from test 这里是统计某一字段共有的记录  
  22. select max(u_id) from test #查询u_id字段中最大值的数据,通常只能是对整型、数字这方面进行比对  
  23. select min(u_id) from test  # 这个就。。。最小值。。。  
  24. select avg(u_id) from test  #查询某一字段的平均值,通常用于查询某什么什么平均年龄或者工资什么的  
  25. select sum(u_id) from test  #查询某一字段的累加值,通常用于查询该字段中共多少工资什么什么的
  仅供参考
相关文章
相关标签/搜索