创建数据:INSERT INTO userinfo(userid,username,job,level1,companyage) VALUES ('001','xl001','test','P1','1'),('002','xl002','test','P1','2'),('003','xl003','test','P1','3'),('004','xl004','test','P1','2'),('005','xl005','test','P1','3'),('006','xl006','test','P2','3'),('007','xl007','mana','P2','2'),('008','xl008','mana','P2','4'),('009','xl009','test','P2','2'),('010','xl010','test','P2','2'),('011','xl011','test','P2','3'),('012','xl012','test','P2','2'),('013','xl013','test','P2','1'),('014','xl014','test','P2','3'),('015','xl015','test','P2','2'),('016','xl016','test','P2','2'),('017','xl017','test','P3','2'),('018','xl018','mana','P3','6'),('019','xl019','mana','P3','4'),('020','xl020','test','P3','2'),('021','xl021','test','P3','2'),('022','xl022','test','P3','7'),('023','xl023','test','P3','2'),('024','xl024','test','P3','5'),('025','xl025','test','P3','2'),('026','xl026','test','P3','1'),('027','xl027','test','P3','2'),('028','xl028','test','P3','2')
----------------------------------------
7. 几个简单的sql语句
插入多条数据:【报错:Duplicate entry '1' for key 'PRIMARY' -- 为主键冲突,检查主键是否有相同的】
INSERT INTO tabname (userid,username,userpwd,employee_id,employee_name,address,tel) VALUES ('001','xl001','password@001','1406081001','tester001','上海浦东新区张东路1388号001号楼','13612345001'),('002','xl002','password@002','1406081002','tester002','上海浦东新区张东路1388号002号楼','13612345002');
查询数据:SELECT * FROM tabname;
删除数据:DELETE FROM tabname WHERE username = 'xl001';
更新表数据:SELECT * FROM tabname WHERE username LIKE '%5';
排序表数据查询:SELECT * FROM tabname ORDER BY username;【desc-倒序、asc-正序】
求总数:SELECT COUNT(*) AS tatalcount FROM tabname;【as-表头命名为tatalcount】
------------
批量更新数据,新增score:
UPDATE tabname SET score = '60' WHERE userid = '2' ;
UPDATE tabname SET score = '61' WHERE userid = '3' ;
UPDATE tabname SET score = '62' WHERE userid = '4' ;
***以此类推
------------
求和:SELECT SUM(score) AS sumscore FROM tabname;
平均:SELECT AVG(score) AS avgscore FROM tabname;
最大:SELECT MAX(score) FROM tabname;
最小:SELECT MIN(score) FROM tabname;
8. 使用外连接
左外连接,left outer join ... on
语句格式:
FROM [表名1] LEFT JOIN [表名2]
ON [表名1.字段A] 〈关系运算符〉[表名2.字段B]
其实LEFT JOIN 的功能就是将LEFT左边的表名1中的所有记录全部保留,而将右边的表名2中的字段B与表名1.字段A相对应的记录显示出来(当使用SELECT * 时)。而RIGHT JOIN 和LEFT JOIN 相反。
right (outer) join:
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
SELECT a.userid,a.address,b.job FROM userbase a RIGHT OUTER JOIN userinfo b ON a.userid = b.userid;
9. 内连接
FROM (((表1 INNER JOIN 表2 ON 表1.字段号=表2.字段号) INNER JOIN 表3 ON 表1.字段号=表3.字段号) INNER JOIN 表4 ON Member.字段号=表4.字段号) INNER JOIN 表X ON Member.字段号=表X.字段号
SELECT a.userid,a.address,b.job FROM userbase a INNER JOIN userinfo b ON a.userid = b.userid;
10. 分组 group by
一张表,一旦分组 完成后,查询后只能得到组相关的信息。
组相关的信息:(统计信息) count,sum,max,min,avg 分组的标准)
SELECT * FROM userinfo GROUP BY companyage;