作为一名测试人,掌握数据库常用的操作不可缺少,下面就一段MySQL 查询语句梳理几个相关语法知识。

本篇文章主要包括两方面内容:

常用的sql语法

开发代码中如何和sql进行关联

案例代码:

`
select a.blastid,d.apptime,a.charge_approve,

            a.blast_batch,

            a.plan_blast_time,

            a.exe_plan_id,

            a.import_flag,

            a.rig_type,.......

            case when (select "count"(*) from bla_geology_info geo where a.blast_id=geo.blast_id and  geo.delete_flag=0)>0

                then 'true' else 'false'  

    END as isShowFlag

    from bla_blast_info a

    left join exe_plan_month b

    on a.exe_plan_id = b.exe_plan_id

    left join sys_user c

    on a.dynamite_user = c.user_id

    left join (select blast_id,isagree,idea,create_time as app_time from bla_charge_approve where delete_flag = '0') d

    on a.blast_id = d.blast_id

    WHERE a.blast_type = '1' AND a.blast_status > '3' AND a.blast_status < '8' AND a.charge_approve > '1' AND a.delete_flag = '0' ORDER BY cast(a.charge_approve  as numeric)  ASC , d.app_time DESC , a.create_time DESC
`

常用的sql语法

1

查询语句 select xxxx from 表名 ,表示从哪个表进行查询。

其中select 后面内容以“,”分割。

2

select xxxx from 表名 别名,表示这个表用别名替代,如上个语句中的a、b、c等。

3

case when then xx,else xxx ,end as isShowFlag表示符合 when 条件执行 then 后面语句,否则执行 else 后面语句。

eg 案例中case when (select “count”(*) from blageologyinfo geo where a.blastid=geo.blastid and geo.delete_flag=0)>0

then ‘true’ else ‘false’ 表示符合条件的爆破量进行上传

end as isShowFlag 起的查询语句别名,后续调用的时候使用别名名称即可。

4

left join 左连接 ,表1左连接表2,以左为主,表示以表1为主,关联上表2的数据,查出来的结果显示左边的所有数据,然后右边显示的是和左边有交集部分的数据。

mysql 软件测试 mysql测试语句_sql


一句话的意思是:先取交集,再关联到左表。

引申整理出几个连接的常用含义及区分 ,如下表所示:

mysql 软件测试 mysql测试语句_mysql 软件测试_02

5

查询语句 select xxxx from 表名 where 查询条件。

where 查询条件后面接所有你要查询的内容,用and连接,这里需要注意order by 使用

order by 1,2,3,4 ,先1排序,1相同的情况下按照2、3、4排序。

6

cast ()数据类型转换函数,文中cast(a.charge_approve as numeric) 表示将字段charge_approve 转换为数字型,以前是字符类型,字符类型的字段不可以进行排序。

7

a.exe_plan_id = b.exe_plan_id 表示 a表的exe_plan_id字段和b表的exe_plan_id 字段进行绑定。

可以这么理解:只有两个表绑定后才能进行相关的查询操作。

总结通用模板:

Select 字段名1,字段名2  case when  条件 then 执行语句  else 执行语句 end as 别名 from 表名 别名 left join on 表连接(a.exe_plan_id = b.exe_plan_id)
Where 查询条件(d.app_time DESC)

开发代码中如何和sql进行关联

开发逻辑中有一个词“mapper映射”,里面具体的实现不做过多赘述。

简单点的逻辑是:用xml文件 将sql 语句的名称 和 实体名称一一映射,通过这种形式进行绑定,然后在代码中引用映射的文件名,从而实现数据查询。

mysql 软件测试 mysql测试语句_数据库_03


上面我们通过一段sql语句列举了MySQL常用的语法,以及sql语句编写完成后 如何在代码中进行使用的。