CREATE TABLE IF NOT EXISTS `mq_info` ( `id` INT(12) UNSIGNED AUTO_INCREMENT COMMENT 'mq信息数据库自增id', `topic` VARCHAR (255) NOT NULL COMMENT 'mq_topic名称', `message` longtext NOT NULL COMMENT 'mq_message内容', `markinfo` VARCHAR (255) COMMENT '该MQ的标识字段', PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8;
查询表中所有数据:
select * from mq_info;
查询表中前20条数据:
select * from mq_info limit 20;
表中新增一条数据:
insert into mq_info (topic, message, markinfo) values ('mq_test', '{"demands":1,"testId":165,"operation":3}', 'testInfo001')
修改表中某个字段的值:
-- 将id=1的数据的topic都改为'mqUpdate_test'update mq_info set topic='mqUpdate_test' where id='1'-- 将id=1或topic='mq_test'的数据的topic都改为'mqUpdate_test',markinfo都改为'testInfo_update'update mq_info set topic='mqUpdate_test', markinfo='testInfo_update' where id='1' or topic='mq_test'
删除表中指定条件的某一条数据:
delete from mq_info where id = 1
删除表中所有的数据:
delete from mq_info
删除表中某一个字段:
-- 删除mq_info表中的markinfo字段alter table mq_info drop column markinfo
-- 复制mq_info表结构生成一张新表order_mq_infocreate table order_mq_info like mq_info
某个字段模糊查询:
-- 查询mq_info表中topic字段包含test的所有数据SELECT * FROM mq_info where topic like '%test%';-- 优化写法:locate(‘substr’,str,pos), 提升查询效率SELECT * FROM mq_info where locate('test', topic)>0
查询条件包含不等于:
-- 查询mq_info表中topic等于'order_info',并且markinfo不等于'test'的所有数据select * from mq_info where topic = 'order_info' and (markinfo != 'test' or markinfo is null)-- 注意加上条件markinfo is null,不然Markinfo为null的数据不会被查出来-- 注意()的作用,加括号是为了提高优先级先执行括号内的查询条件-- 在这个基础上再进行topic = 'order_info'的查询
分组+条件查询:
-- 查询每个老师带的学生的平均年龄(group by语法)-- 由于是查每个老师,因此要用TeacherID作为分组条件select TeacherID, avg(Age) as AGE from student group by TeacherID-- 查询每个老师带的学生的平均年龄且平均年龄大于12(group by + having语法)-- 条件是带函数的,就必须用having,而不能用whereselect TeacherID, avg(Age) as AGE from student group by TeacherID having avg(Age) > 12
连表查询,主表所有字段+从表部分字段:
-- teacher表中没有存学生姓名,只存了学生id-- 需要将teacher表中create_time大于等于2022-10-28 00:00:00的所有数据以及学生的姓名查出来select teacher.*,student.studentName,from teacher_manage replay LEFT JOIN student_manage student on teacher.student_id=student.id where teacher.create_time >= '2022-10-28 00:00:00';