MySql数据库常用DML | 黄乔国PHP

来源:互联网 发布:小企业it整体解决方案 编辑:程序博客网 时间:2024/06/02 02:07

MySQL中数据操作语言DML总结。

再MySQL中我们用的最多的就是DML了,特此总结一下。

DML主要分为增删查改,即CURD也就是对应到:insert/update/select/delete

一、插入数据相关

①全部插入

insert into tab_name values(字段值1,字段值2,字段值n);
②部分字段插入

insert into tab_name(字段1,字段2,字段n) values(字段值1,字段值2,字段值n);
③多条数据同时插入

insert into tab_name values(字段值1,字段值2,字段值n),(字段值1,字段值2,字段值n),(字段值1,字段值2,字段值n)....(字段值1,字段值2,字段值n);

二、更新数据

①单字段更新

update tab_name set 字段名=新字段值 [where条件]
②多字段更新

update tab_name set 字段名1=新字段值,字段名2=新字段值,....字段名2=新字段值 [where条件]


三、数据查询(DML中的重中之重)

①全查询

select * from tab_name [where条件];
②按需查询

select 字段名1,字段名2,...字段名n from tab_name [where 条件];
③排序查询:order by(asc 升序,desc 降序)

select * from tab_name [where 条件]  order by 排序字段名 [asc | desc];
④分组查询:group by
select * from tab_name [where 条件] group by 分组字段名;
⑤包含having的查询

传送门:http://blog.csdn.net/love_xsq/article/details/42417917

⑥多表查询

select * from tab1 as t1,tab2 as t2 where t1.id=t2.id; 
⑦join查询

left join:以左表数据为基准

select * from tab1 t1 LEFT JOIN tab2 t2 ON t1.id=t2.id [where 条件]
right join:以右表数据为基准
select * from tab1 t1 RIGHT JOIN tab2 t2 ON t1.id=t2.id [where 条件] [group by] [order by]....;
inner join:以共有数据为基准
select * from tab1 t1 INNER JOIN tab2 t2 ON t1.id=t2.id [where 条件] [group by] [order by]....;
 ⑧限制查询:limit
limit 有两个参数,limit start,length
如果只有一个参数则参数表示length即:limit length,开始则从始终从0开始。
//查询前五条记录select * from tab limit 5;//查询6到10条记录select * from tab limit 5,5;

⑨模糊查询:like
//全模糊select * from tab where tab.字段名 like "%值%";//以什么开始select * from tab where tab.字段名 like "值%";//以什么结束select * from tab where tab.字段名 like "%值";//占位符:一个 _ 占一个字符select * from tab where tab.字段名 like "_值";
如果查询的内容里面包括%,_那么我们就应该使用escape
select * from tab where tab.字段名 like "%\%" escape "\\";//以百分号结束
 注意没有使用 \ 转义的字符依然表示原来的意思。
⑩正则查询:REGEXP | RLIKE  []
select * from tab where tab.字段名 REGEXP "a[123]";
上面的sql语句将匹配字段名中包括a1或a2或a3。
语法就是正则的语法。
①①.子查询
1.where型子查询
select cat_id,goods_id,goods_name from goods where goods_id in(select max(goods_id) from goods group by cat_id);
 2.from型子查询
select name from (select name,count(*) as gk from stu having gk >=2) as t;
 3.exists型子查询(把外层查询结果拿到内层,看内层的查询是否成立)
#查询哪些栏目下有商品,栏目表category,商品表goodsselect cat_id,cat_name from category where exists(select * from goods where goods.cat_id = category.cat_id);
 ①②去重查询:distinct
select distinct 字段名1,字段名2,....字段名n from tab;
注意:distinct只能放在字段前面
①③合并查询:union
把两个查询的结果合并起来,单字段必须一致。
union:会自动去除掉相同的行
union all:不会去掉相同的行


四、删除相关:delete
delete from tab [where];

以上是MySQL常用DML语句,如有遗漏请留言,后期会补上








原创粉丝点击