INSERT
基本语法:INSERT INTO table_name VALUES(value1,value2,value3,...);
指定列:INSERT INTO table_name(column1, column2, column3,…) VALUES(value1,value2,value3,...);
UPDATE
UPDATE table_name set column1='new_value',column2='new_value',...;
mysql 的跨表UPDATE
假定我们有两张表,一张表为Product表存放产品信息,其中有产品价格列Price;另外一张表是ProductPrice表,我们要将ProductPrice表中的价格字段Price更新为Product表中价格字段的80%。
(1)update product p, productPrice pp set pp.price = p.price * 0.8 where p.productId = pp.productId and p.dateCreated < '2004-01-01';
(2)update product p inner join productPrice pp on p.productId = pp.productId set pp.price = p.price * 0.8 where p.dateCreated < '2004-01-01';
我们也可以使用left outer join来做多表update,比方说如果ProductPrice表中没有产品价格记录的话,将Product表的isDeleted字段置为1
update product p left join productPrice pp on p.productId = pp.productId set p.deleted = 1 where pp.productId is null
上面的几个例子都是两张表之间做关联,但是只更新一张表中的记录,其实是可以同时更新两张表的
update product p inner join productPrice pp on p.productId = pp.productId set pp.price = pp.price * 0.8, p.dateUpdate = curdate() where p.dateCreated < '2004-01-01'
DELETE
DELETE from table_name;
SELECT
SELECT column1,column2,column3,... from table_name; or
SELECT * from table_name;
WHERE condition GROUP BY column1,column2,...HAVING condition
分组要有据(select columns 有该字段),先有结果集(可以是where帅选过的),再依据唯一性分组,然后统计,最后过滤结果集。
a sample Employees table
求各个部门的总工资:
SELECT DEPARTMENT_ID,SUM(SALARY) as Total_Salary FROM EmployeesGROUP BY DEPARTMENT_ID;
group by DEPARTMENT_ID后具有相同DEPARTMENT_ID的数据项聚集在一起,然后以函数的形式合并成一条记录,DEPARTMENT_ID具备了唯一性(group by后的字段组合具有唯一性)。
左连接: select column1,column2 from table1 left join table2 on <两表某条数据项连接在一起的条件> where <过滤条件>;
符合<过滤条件>的左侧表的数据项出现次数大于等于1.