MySQL----数据表内容操作(语法篇)

mysql内置函数

  https://www.runoob.com/mysql/mysql-functions.html

 表内容操作: 

1、增

insert into 表 (列名,列名...) values (值,值,值...)
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from 表
INSERT INTO 表 VALUES (DEFAULT,"xsss",DEFAULT) //如果不填写字段,values后面的所有的字段都需要填写,不需要写的,可以填default

SELECT LAST_INSERT_ID(); //返回主键

2、删

删除数据一般不使用下面的sql语句,我们使用假性删除,给每一行数据加上一个是否删除字段,删除的时候把这个字段变成0,查询的时候判断条件为1

delete from 表      #删除表中的所有的数据
delete from 表 where id=1 and name='alex'
DELETE FROM tbuser WHERE id IN (12,13)
DELETE FROM tbuser WHERE id BETWEEN 16 AND 20

3、改

UPDATE 表 set name = 'alex' where id>1
UPDATE employee SET dept = dept+1 WHERE id = 1;  //对数据库中的dept字段自增1

4、查

select * from 表              
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1

SELECT COUNT(*) FROM t_user WHERE username="yy";  //返回查询的数目
SELECT * FROM logininfo LIMIT 4,10;               //第5行数据开始一个10条数据 limit 4,-1(最后一行),如果数据不够10条,直接返回实际的数目

4.1子查询

SELECT 
  *,
  (SELECT 
    ordername 
  FROM
    u_order 
  WHERE t_user.`order_id` = u_order.`id`) AS ordername    //根据t_user.order_id 来关联查询的
FROM
  t_user ;

5、其他

a、条件
    select * from 表 where id > 1 and name != 'alex' and num = 12;
 
    select * from 表 where id between 5 and 16;
 
    select * from 表 where id in (11,22,33)
    select * from 表 where id not in (11,22,33)
    select * from 表 where id in (select nid from 表)
 
b、通配符
    select * from 表 where name like 'ale%'  - ale开头的所有(多个字符串)
    select * from 表 where name like 'ale_'  - ale开头的所有(一个字符)
 
c、限制
    select * from 表 limit 5;            - 前5行
    select * from 表 limit 0,5           - 钱5行(从第0行开始),和limit 5 一样
    select * from 表 limit 4,5;          - 从第4行开始的5行
    select * from 表 limit 5 offset 4    - 从第4行开始的5行
 
d、排序
    select * from 表 order by 列 asc              - 根据 “列” 从小到大排列
    select * from 表 order by 列 desc             - 根据 “列” 从大到小排列
    select * from 表 order by 列1 desc,列2 asc    - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
    ORDER BY colum asc IF(ISNULL(colum),0,1) //null被强制放在最前,不为null的按声明顺序[asc|desc]进行排序
   ORDER BY colum asc IF(ISNULL(colum),1,0) //null被强制放在最后,不为null的按声明顺序[asc|desc]进行排序
 
e、分组
    select num from 表 group by num
    select num,nid from 表 group by num,nid
    select num,nid from 表  where nid > 10 group by num,nid order nid desc
    select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
 
    select num from 表 group by num having max(id) > 10
 
    特别的:group by 必须在where之后,order by之前
 
f、连表
    无对应关系则不显示
    select A.num, A.name, B.name
    from A,B
    Where A.nid = B.nid
 
    无对应关系则不显示
    select A.num, A.name, B.name
    from A inner join B
    on A.nid = B.nid
 
    A表所有显示,如果B中无对应关系,则值为null
    select A.num, A.name, B.name
    from A left join B
    on A.nid = B.nid
 
    B表所有显示,如果B中无对应关系,则值为null
    select A.num, A.name, B.name
    from A right join B
    on A.nid = B.nid
 
g、组合
    组合,自动处理重合
    select nickname
    from A
    union
    select name
    from B
 
    组合,不处理重合
    select nickname
    from A
    union all
    select name
    from B

IFNULL

SELECT 
  a.`id`,
  a.`name`,
  b.`id`,
  IFNULL(b.`name`,'/')    //如果查询为null,可以设置一个默认值
FROM
  tb_content_category AS a 
  LEFT JOIN tb_content_category AS b 
    ON a.`parent_id` = b.`id` 

EXISTS和Insert配合使用

有问题?参考:https://www.cnblogs.com/chucklu/p/10482311.html

IF NOT EXISTS (SELECT * FROM logininfo WHERE username="stdf")
BEGIN
	INSERT INTO logininfo(username,PASSWORD) VALUES("xx","xx")
END

  (执行student.length次)对于下面的sql语句首先执行的语句是select * from student s,在根据表的每一条记录,执行以下语句(EXISTS(select stuid from score ss where ss.stuid = s.stuid)),依次去判断where后面的条件是否成立:如果成立则返回true不成立则返回false。如果返回的是true的话,则该行结果保留,如果返回的是false的话,则删除该行,最后将得到的结果返回

select * from student s where EXISTS(select stuid from score ss where ss.stuid = s.stuid)
<insert id="insertSelection" parameterType="net.microcarystal.sport.pojo.master.CourseStudentSelection">
        <selectKey keyProperty="id" order="AFTER" resultType="long">
            select LAST_INSERT_ID();
        </selectKey>
        insert into course_student_selection
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="status != null">
                status,
            </if>
            <if test="schoolId != null">
                schoolId,
            </if>
            <if test="stuId != null">
                stuId,
            </if>
            <if test="yearId != null">
                yearId,
            </if>
            <if test="courseId != null">
                courseId,
            </if>
            <if test="scheduleId != null">
                scheduleId,
            </if>
            <if test="sportStageId != null">
                sportStageId,
            </if>
            <if test="sportItemId != null">
                sportItemId,
            </if>
            <if test="updateTime != null">
                updateTime,
            </if>
            <if test="createTime != null">
                createTime,
            </if>
            <if test="createUser != null">
                createUser,
            </if>
            <if test="updateUser != null">
                updateUser,
            </if>
        </trim>
        select
        <trim  suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=BIGINT},
            </if>
            <if test="status != null">
                #{status,jdbcType=INTEGER},
            </if>
            <if test="schoolId != null">
                #{schoolId,jdbcType=BIGINT},
            </if>
            <if test="stuId != null">
                #{stuId,jdbcType=BIGINT},
            </if>
            <if test="yearId != null">
                #{yearId,jdbcType=BIGINT},
            </if>
            <if test="courseId != null">
                #{courseId,jdbcType=BIGINT},
            </if>
            <if test="scheduleId != null">
                #{scheduleId,jdbcType=BIGINT},
            </if>
            <if test="sportStageId != null">
                #{sportStageId,jdbcType=BIGINT},
            </if>
            <if test="sportItemId != null">
                #{sportItemId,jdbcType=BIGINT},
            </if>
            <if test="updateTime != null">
                #{updateTime,jdbcType=TIMESTAMP},
            </if>
            <if test="createTime != null">
                #{createTime,jdbcType=TIMESTAMP},
            </if>
            <if test="createUser != null">
                #{createUser,jdbcType=BIGINT},
            </if>
            <if test="updateUser != null">
                #{updateUser,jdbcType=BIGINT},
            </if>
        </trim>
        from DUAL where 1=(SELECT count(1) FROM course_schedule  a
        left join user_info b on b.id=#{stuId}
        left join course_student_selection c on c.stuId=b.id and c.scheduleId = a.id and c.`status`=1
        WHERE c.id is null and a.id = #{scheduleId} and a.lastLim>0 and (a.genderLim!=3 or (a.genderLim=3 and b.userSex=0 AND (femaleScale-femaleCount)>0) or (genderLim=3 AND b.userSex=1 AND (maleScale-maleCount)>0)))
    </insert>
mysql> 
    ->INSERT INTO  test_book1
    ->   SELECT 1, 'TEST', 'ABC' FROM dual
    ->   WHERE NOT EXISTS( SELECT 1 FROM test_book1 WHERE id = 1);

IN

  (只执行一次),in在查询的时候,首先查询子查询的表,然后将内表和外表做一个笛卡尔积,然后按照条件进行筛选。所以相对内表比较小的时候,in的速度较快。

首先会执行from语句找出student表,然后执行 in 里面的子查询,再然后将查询到的结果和原有的user表做一个笛卡尔积,再根据我们的student.stuid IN score.stuid的条件,将结果进行筛选(既比较stuid列的值是否相等,将不相等的删除)。最后,得到符合条件的数据。

select * from student s where s.stuid in(select stuid from score ss where ss.stuid <1005)

  in 和 exists的区别: 如果子查询得出的结果集记录较少,主查询中的表较大且又有索引时应该用in, 反之如果外层的主查询记录较少,子查询中的表大,又有索引时使用exists。

  in 是把外表和内表作hash 连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询。一直以来认为exists比in效率高的说法是不准确的。

  如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。 

Unique

  首先建表的时候给name设置为unique

  不存在则插入,存在则更新(on duplicate key update)

    如果数据库中有一条数据name = “jack”(因为name设置了unique,插入数据会造成冲突),那么我们继续update操作,更新年龄是19,否则就正常插入操作

INSERT INTO `student`(`name`, `age`) VALUES('Jack', 19) ON DUPLICATE KEY UPDATE `age`=19;

  先删除旧数据再插入最新的数据(replace into)

REPLACE INTO `student`(`name`, `age`) VALUES('Jack', 18); 

  避免重复插入(insert ignore into)

INSERT IGNORE INTO `student`(`name`, `age`) VALUES('Jack', 18);

Group By

  group By 和聚合函数:https://blog.csdn.net/u014717572/article/details/80687042

  当使用group By的时候,sql首先执行Group 在进行条件判断,如果希望group By的时候对某些字段不进行group By可以在条件中进行判断

比如:这种startYear=2019的数据就不会查出来

SELECT  * FROM school_year WHERE STATUS = 1 AND schoolId = 1 AND (startYear != 2019) GROUP BY startYear ORDER BY startYear DESC

我们就可以使用or方法并添加条件来将startYear的数据查询出来

SELECT  * FROM school_year WHERE STATUS = 1 AND schoolId = 1 AND (startYear != 2019 OR isThisYear=1) GROUP BY startYear ORDER BY startYear DESC

Case

  如果字段中没有#{},比如genderLim,就会从数据库中的字段来查

And (CASE genderLim WHEN 1 THEN #{userSex} = 1 WHEN 2 THEN #{userSex} = 0 ELSE 1=1 END)

 

  select
        a.id as id,
        d.courseName as courseName,
        (case b.weekTimes when 1 then '星期一'
            when 2 then '星期二'
            when 3 then '星期三'
            when 4 then '星期四'
            when 5 then '星期五'
            when 6 then '星期六'
            when 7 then '星期日'
            else null end)
        as weekTimes,
        b.beginTimes as beginTimes,
        from attend_calendar

IF

  IF(expr1,expr2,expr3),如果expr1的值为true,则返回expr2的值,如果expr1的值为false

and if((`v`.`rangeTYPE`= '2'),(`v`.`rangeID`= `s`.`SCHOOL_ID`),(`v`.`parentId`= `s`.`SCHOOL_ID`))

concat

  可以将返回的字段进行拼接

SELECT CONCAT(user_info.`userCode`,'-',user_info.`userName`) AS userCodeAndUserName FROM user_info WHERE
user_info.`status`=1 AND user_info.`userType`=2 AND schoolId=1 LIMIT 0,20

update关联

        update course_schedule
        set totalCount = totalCount+1, lastLim = lastLim-1,
        maleCount = maleCount + (select ifnull(count(*),0) as maleCount from user_info where id=#{stuId} and userSex=1),
        femaleCount = femaleCount + (select ifnull(count(*),0) as maleCount from user_info where id=#{stuId} and userSex=0)
        where id = #{scheduleId,jdbcType=BIGINT}

正则

select * from tb where name regexp ’z’; 

on和where的用法

无论LEFT JOIN  ON后面什么条件,都不影响主表数据被查询数来(只是关联表没有数据而已)

参考:https://www.cnblogs.com/FENGXUUEILIN/p/10040025.html

SELECT
    stu.*
FROM
    student stu
 LEFT JOIN grade gra on stu.id = gra.c_stuId
WHERE gra.c_fs is NOT null

执行顺序  

Where, Group By, Having, Order by

Insert into

https://www.w3school.com.cn/sql/sql_select_into.asp

  • 把某些字段插入新表
SELECT colum1,colum2 INTO new_table FROM SYS_BUSINESS_SEQNUM
  • 如果在函数里面,可以查询的数据赋值到另一个数据
iseqnum :=1;
SELECT SEQNUM  INTO iseqnum FROM SYS_BUSINESS_SEQNUM

  

原文地址:https://www.cnblogs.com/yanxiaoge/p/11155231.html