为了方便执行语句,这里在MySQL Workbench上进行数据库连接操作。在上一篇创建的user表进行操作,user_id字段使用UUID作为唯一键,可以用mysql的UUID函数生成:
1. 增
INSERT INTO iHouse.user(user_name, user_id, last_login_date, email_addr) VALUES ('LinJK', '758259ad-04cb-11e7-9d4a-52540036b0ab', '2017-03-09', 'test@localhost.com');
可以同时插入多条数据,在values后面用逗号分隔需要插入的多条数据即可。
再次执行该语句,报如下错误,说明UUID一样,唯一键可以防止数据重复插入:
2. 删
DELETE FROM iHouse.user where id=4;
3. 改
UPDATE iHouse.user set email_addr='haha@localhost.com' where id=3;
4. 查
SELECT * FROM iHouse.user;
SELECT * FROM iHouse.user where id=3 and user_name='LinJK';
插入部分数据后:
去重查询(邮件重复的去掉):
SELECT DISTINCT email_addr FROM iHouse.user;
排序查询(DESC降序 ASC升序)
SELECT * FROM iHouse.user order by id desc;
也可使用limit关键字控制输出结果数量
查询记录数:
SELECT COUNT(*) from iHouse.user; 或 SELECT COUNT(1) from iHouse.user;
根据某个字段查询统计每个字段的数量:
SELECT email_addr, COUNT(1) FROM iHouse.user GROUP by email_addr;
根据某个字段查询统计每个字段的数量,再汇总总数:
SELECT email_addr, COUNT(1) FROM iHouse.user GROUP by email_addr with rollup;
根据某个字段查询统计每个字段的数量,统计出数量大于1的:
SELECT email_addr, COUNT(1) FROM iHouse.user GROUP by email_addr having count(1)>1;
另外还有表连接查询和子查询,这里只有一个表就暂时不测试了,通常,表连接在很多情况下用于优化子查询,还有可以两个表数据查询后一起展示,这会用到union或union all关键字。