在这篇文章中,我们将带领您了解SQL逻辑问题和交叉应用查询的全貌,包括sql逻辑问题和交叉应用查询的区别的相关情况。同时,我们还将为您介绍有关2-MySQL:SQL逻辑查询语句执行顺序、FluentM
在这篇文章中,我们将带领您了解SQL逻辑问题和交叉应用查询的全貌,包括sql逻辑问题和交叉应用查询的区别的相关情况。同时,我们还将为您介绍有关2 - MySQL:SQL逻辑查询语句执行顺序、Fluent Mybatis如何做到代码逻辑和sql逻辑的合一、HANA SQL联接替代交叉应用/横向、MS-SQLServer 2000 T-SQL 交叉报表(行列互换) 交叉查询 旋转查询的知识,以帮助您更好地理解这个主题。
本文目录一览:- SQL逻辑问题和交叉应用查询(sql逻辑问题和交叉应用查询的区别)
- 2 - MySQL:SQL逻辑查询语句执行顺序
- Fluent Mybatis如何做到代码逻辑和sql逻辑的合一
- HANA SQL联接替代交叉应用/横向
- MS-SQLServer 2000 T-SQL 交叉报表(行列互换) 交叉查询 旋转查询
SQL逻辑问题和交叉应用查询(sql逻辑问题和交叉应用查询的区别)
给定开始日期和结束日期,我需要计算这两个日期之间的实例数。因此,给出以下内容:
桌子:
Col 1 Start_Date End_Date
1 01/01/2010 02/01/2010
2 01/01/2010 04/01/2010
3 03/01/2010 04/01/2010
4 03/01/2010 04/01/2010
如果我在第一个(01/01)和第二个(02/01)之间看,我希望计数为2。如果我在寻找第3个到第4个,则期望计数为3。在整个日期范围内,那么我希望计数为4。有意义吗?
注意: 日期已转换为午夜,无需为此添加任何代码。此外,在整个问题中,日期均为dd / MM / yyyy格式。
目前,我有类似以下内容:
SELECT COUNT(*),Group_Field
FROM MY_Table
WHERE Start_Date < DATEADD(DAY,1,@StartDate) AND End_Date > @EndDate
GROUP BY Group_Field
我曾经认为这是对的,但现在我不敢相信…
我以前有:
WITH Dates AS (
SELECT [Date] = @StartDate
UNION ALL SELECT [Date] = DATEADD(DAY,[Date])
FROM Dates WHERE [Date] < @EndDate
)
SELECT COUNT(*),Group_Field -- In this case it is [Date]
FROM MY_Table
CROSS APPLY Dates
WHERE Start_Date < DATEADD(DAY,@StartDate) AND End_Date > [Date]
GROUP BY Group_Field
但是我不确定在这种情况下我是否正确使用了CROSS APPLY …
问题:
1)我是否在第二个示例中使用了交叉申请(以及与此相关的CTE)?
2)如果是,哪种逻辑是正确的?(我认为这是第二个)
/讨论 :)
2 - MySQL:SQL逻辑查询语句执行顺序
MySQL:SQL逻辑查询语句执行顺序
一,SELECT语句关键字的定义顺序
SELECT DISTINCT <select_list>
FROM <left_table>
<join_type> JOIN <right_table>
ON <join_condition>
WHERE <where_condition>
GROUP BY <group_by_list>
HAVING <having_condition>
ORDER BY <order_by_condition>
LIMIT <limit_number>
二,SELECT语句关键字的执行顺序
(7) SELECT
(8) DISTINCT <select_list>
(1) FROM <left_table>
(3) <join_type> JOIN <right_table>
(2) ON <join_condition>
(4) WHERE <where_condition>
(5) GROUP BY <group_by_list>
(6) HAVING <having_condition>
(9) ORDER BY <order_by_condition>
(10) LIMIT <limit_number>
Fluent Mybatis如何做到代码逻辑和sql逻辑的合一
对比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?很多朋友对这一问题不是很清楚,今天小编给大家带来一篇教程关于Fluent Mybatis如何做到代码逻辑和sql逻辑的合一,一起看看吧
使用fluent mybatis可以不用写具体的xml文件,通过java api可以构造出比较复杂的业务sql语句,做到代码逻辑和sql逻辑的合一。不再需要在Dao中组装查询或更新操作,在xml或mapper中再组装参数。那对比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?
场景需求设置
我们通过一个比较典型的业务需求来具体实现和对比下,假如有学生成绩表结构如下:
create table `student_score` ( id bigint auto_increment comment '主键ID' primary key, student_id bigint not null comment '学号', gender_man tinyint default 0 not null comment '性别, 0:女; 1:男', school_term int null comment '学期', subject varchar(30) null comment '学科', score int null comment '成绩', gmt_create datetime not null comment '记录创建时间', gmt_modified datetime not null comment '记录最后修改时间', is_deleted tinyint default 0 not null comment '逻辑删除标识' ) engine = InnoDB default charset=utf8;
现在有需求:
统计2000年三门学科('英语', '数学', '语文')及格分数按学期,学科统计最低分,最高分和平均分, 且样本数需要大于1条,统计结果按学期和学科排序
我们可以写sql语句如下:
select school_term, subject, count(score) as count, min(score) as min_score, max(score) as max_score, avg(score) as max_score from student_score where school_term >= 2000 and subject in ('英语', '数学', '语文') and score >= 60 and is_deleted = 0 group by school_term, subject having count(score) > 1 order by school_term, subject;
那上面的需求,分别用fluent mybatis, 原生mybatis 和 Mybatis plus来实现一番。
三者对比
使用fluent mybatis 来实现上面的功能
我们可以看到fluent api的能力,以及IDE对代码的渲染效果。
代码:https://gitee.com/fluent-mybatis/fluent-mybatis-docs/tree/master/spring-boot-demo/
换成mybatis原生实现效果
1. 定义Mapper接口
public interface MyStudentscoreMapper { List> summaryscore(SummaryQuery paras); }
2. 定义接口需要用到的参数实体 SummaryQuery
@Data @Accessors(chain = true) public class SummaryQuery { private Integer schoolTerm; private List subjects; private Integer score; private Integer minCount; }
3. 定义实现业务逻辑的mapper xml文件
select school_term, subject, count(score) as count, min(score) as min_score, max(score) as max_score, avg(score) as max_score from student_score where school_term >= #{schoolTerm} and subject in #{item} and score >= #{score} and is_deleted = 0 group by school_term, subject having count(score) > #{minCount} order by school_term, subject
4. 实现业务接口(这里是测试类, 实际应用中应该对应Dao类)
@RunWith(springrunner.class) @SpringBoottest(classes = QuickStartApplication.class) public class MybatisDemo { @Autowired private MyStudentscoreMapper mapper; @Test public void mybatis_demo() { SummaryQuery paras = new SummaryQuery() .setSchoolTerm(2000) .setSubjects(Arrays.asList("英语", "数学", "语文")) .setscore(60) .setMinCount(1); List> summary = mapper.summaryscore(paras); System.out.println(summary); } }
总之,直接使用mybatis,实现步骤还是相当的繁琐,效率太低。那换成mybatis plus的效果怎样呢?
换成mybatis plus实现效果
mybatis plus的实现比mybatis会简单比较多,实现效果如下:
如红框圈出的,写mybatis plus实现用到了比较多字符串的硬编码(可以用Entity的get lambda方法部分代替字符串编码)。字符串的硬编码,会给开发同学造成不小的使用门槛,个人觉的主要有2点:
1. 字段名称的记忆和敲码困难
2. Entity属性跟随数据库字段发生变更后的运行时错误
其他框架,比如TkMybatis在封装和易用性上比mybatis plus要弱,就不再比较了。
生成代码编码比较
fluent mybatis生成代码设置
public class AppEntityGenerator { static final String url = "jdbc:MysqL://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8"; public static void main(String[] args) { FileGenerator.build(Abc.class); } @Tables( /** 数据库连接信息 **/ url = url, username = "root", password = "password", /** Entity类parent package路径 **/ basePack = "cn.org.fluent.mybatis.springboot.demo", /** Entity代码源目录 **/ srcDir = "spring-boot-demo/src/main/java", /** Dao代码源目录 **/ daoDir = "spring-boot-demo/src/main/java", /** 如果表定义记录创建,记录修改,逻辑删除字段 **/ gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted", /** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/ tables = @Table(value = {"student_score"}) ) static class Abc { } }
mybatis plus代码生成设置
public class CodeGenerator { static String dbUrl = "jdbc:MysqL://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8"; @Test public void generateCode() { GlobalConfig config = new GlobalConfig(); DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MysqL) .setUrl(dbUrl) .setUsername("root") .setPassword("password") .setDriverName(Driver.class.getName()); StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig .setCapitalMode(true) .setEntityLombokModel(false) .setNaming(NamingStrategy.underline_to_camel) .setColumnNaming(NamingStrategy.underline_to_camel) .setEntityTableFieldAnnotationEnable(true) .setFieldPrefix(new String[]{"test_"}) .setInclude(new String[]{"student_score"}) .setLogicDeleteFieldName("is_deleted") .setTableFillList(Arrays.asList( new TableFill("gmt_create", FieldFill.INSERT), new TableFill("gmt_modified", FieldFill.INSERT_UPDATE))); config .setActiveRecord(false) .setIdType(IdType.AUTO) .setoutputDir(System.getProperty("user.dir") + "/src/main/java/") .setFileOverride(true); new AutoGenerator().setGlobalConfig(config) .setDataSource(dataSourceConfig) .setStrategy(strategyConfig) .setPackageInfo( new PackageConfig() .setParent("com.mp.demo") .setController("controller") .setEntity("entity") ).execute(); } }
看完3个框架对同一个功能点的实现, 各位看官肯定会有自己的判断,笔者这里也总结了一份比较。
链接:juejin.cn/post/6886019929519177735
到此这篇关于Fluent Mybatis如何做到代码逻辑和sql逻辑的合一的文章就介绍到这了,更多相关Fluent Mybatis代码逻辑和sql逻辑的合一内容请搜索小编以前的文章或继续浏览下面的相关文章希望大家以后多多支持小编!
HANA SQL联接替代交叉应用/横向
您可能想尝试使用相关子查询而不是ROW_NUMBER()
:
select ...
from sapecc.aufk as a
left join sapecc.jcds as j
on j.objnr = a.objnr
and j.mandt = a.mandt
and j.stat = 'I0045'
and j.inact = ''
and j.udate = (
select max(j1.udate)
from sapecc.jcds as j1
where
j1.objnr = a.objnr
and j1.mandt = a.mandt
and j1.stat = 'I0045'
and j1.inact = ''
)
此查询应利用(objnr,mandt,stat,inact,udate desc)
上的索引。
您可以将MSSQL与HANA所用的CTE方法相同:
WITH most_recent_JCDS as (
SELECT * FROM (
SELECT *,ROW_NUMBER()
OVER (PARTITION BY MANDT,OBJNR
ORDER BY UDATE DESC) AS RowNumber
FROM SAPECC.JCDS
WHERE STAT = 'I0045'
AND INACT = '')
WHERE
RowNumber = 1)
SELECT
AUFK. ...,JCDS. ...
FROM
SAPECC.AUFK AUFK
LEFT OUTER JOIN most_recent_JCDS JCDS
ON
(JCDS.OBJNR,JCDS.MANDT)
= (AUFK.OBJNR,AUFK.MANDT);
关于性能或查询效率的担忧只能通过检查实际执行来解决。 PlanViz和EXPLAIN PLAN是实现此目的的工具。
假设某些索引“应该”帮助提供了50/50的机会来使其正确(最好)。
MS-SQLServer 2000 T-SQL 交叉报表(行列互换) 交叉查询 旋转查询
在MS-sqlServer 2005和oracle 中可以使用Pivot 和 Unpivot来做行列转换,不过不支持动态列哦。
在这里使用 case when then else end 语句,来实现行列转换. 如何实现动态列在最下面。
下面以学生成绩表来举例:
id姓名 科目 成绩
1 张三 语文 60
2 张三 数学 65
3 张三 外语 70
4 李四 语文 80
5 李四 数学 90
6 李四 外语 85
7 王五 语文 70
8 王五 数学 71
9 王五 外语 75
10 赵六 语文 64
11 赵六 数学 67
12 赵六 外语 76
查询后得出:
姓名 语文数学外语
李四 80 90 85
王五 70 71 75
张三 60 65 70
赵六 64 67 76
准备数据:
select * from sysobjects where [xtype]='u'
go
if exists(select id from sysobjects where name='studentscore')
drop table studentscore--删除与实验冲突的表
go
create table studentscore--创建实验表
(
[id] int identity(1,1),
[name] nvarchar(20) not null,
subject nvarchar(20) not null,
score int not null
)
go
select * from studentscore
go
--添加实验数据
insert studentscore values ('张三','语文','60');
insert studentscore values ('张三','数学','65');
insert studentscore values ('张三','外语','70');
insert studentscore values ('李四','80');
insert studentscore values ('李四','90');
insert studentscore values ('李四','85');
insert studentscore values ('王五','70');
insert studentscore values ('王五','71');
insert studentscore values ('王五','75');
insert studentscore values ('赵六','64');
insert studentscore values ('赵六','67');
insert studentscore values ('赵六','76');
go
select * from studentscore
go
我们先利用case when then else end 语句将行转为列:
select [name],语文=case when subject='语文' then score else 0 end from studentscore group by [name],subject,score
这里为了好理解只取一列,得到下面的结果
有了语文成绩行专列的例子后,我们很容易将其他两列也添加进来,
select [name],
语文=case
when subject='语文' then score else 0
end,
数学=case
when subject='数学' then score else 0
end,
外语=case
when subject='外语' then score else 0
end
from studentscore
group by [name],score
下面是查询后的结果:
现在只要把name相同的行合并到一起就ok了,
语文=max(case
when subject='语文' then score else 0
end),
数学=max(case
when subject='数学' then score else 0
end),
外语=max(case
when subject='外语' then score else 0
end)
from studentscore
group by [name]
好了,看看结果吧.
上面是列数可枚举时的代码,很多情况下到底有多少列是动态的或者不可知的.
这个时候需要拼下sql语句了.
declare @sql varchar(8000)
set @sql = 'select [name],'
select @sql = @sql + 'sum(case subject when '''+subject+'''
then score else 0 end) as '''+subject+''','
from (select distinct subject from studentscore) as a
select @sql = left(@sql,len(@sql)-1) + ' from studentscore group by [name]'
exec(@sql)
这个语句还可以再优化些,呵呵.
end
关于SQL逻辑问题和交叉应用查询和sql逻辑问题和交叉应用查询的区别的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于2 - MySQL:SQL逻辑查询语句执行顺序、Fluent Mybatis如何做到代码逻辑和sql逻辑的合一、HANA SQL联接替代交叉应用/横向、MS-SQLServer 2000 T-SQL 交叉报表(行列互换) 交叉查询 旋转查询等相关知识的信息别忘了在本站进行查找喔。
本文标签: