赞
踩
示例一:
需求:取类型为1且创建时间小于等于dateStr="2022-01"的项目。
1.数据库中的创建时间为日期类型,需格式为年月的格式与传进来的开始日期进行匹配
2.条件构造器apply的查询方式解决日期和时间之间查询上的冲突
- projectMapper.selectList(new LambdaQueryWrapper<Project>()
- .eq(Project::getType,1)
- .and(qw -> qw.apply("DATE_FORMAT(create_time, '%Y-%m') <= '" + dateStr + "'")));
执行SQL如下:
- SELECT
- *
- FROM project
- WHERE
- type = 1
- AND (DATE_FORMAT(create_time, '%Y-%m') <= '2022-01');
示例二
and中的or,和外层的or,看sql,有助于理解。
- // 示例二
- customerMapper.selectList(new LambdaQueryWrapper<Customer>()
- .eq(Customer::getTaxpayerIdentificationNumber,"912102113000000000")
- .and(qw -> qw.eq(Customer::getParentId,111).or().eq(Customer::getContactNumber,"88"))
- .eq(Customer::getName, "啦啦啦")
- .or()
- .ne(Customer::getNumber, 1)
- .eq(Customer::getCompanyType,1));
执行SQL如下:
- SELECT
- *
- FROM
- customer
- WHERE
- taxpayer_identification_number = '912102113000000000'
- AND (
- parent_id = 111
- OR contact_number = '88'
- )
- AND NAME = '啦啦啦'
- OR number <> 1
- AND company_type = 1;
示例三:
需求:查截止到今天,未下项目的数据。
under_project_time为下项目时间
使用条件构造器apply查询方式可以直接把格式一样当前日期和下项目时间进行比较筛选
- employeeProjectMapper.selectList(new LambdaQueryWrapper<EmployeeProject>()
- .isNotNull(EmployeeProject::getState)
- .eq(EmployeeProject::getFlag, 1)
- .and(qw -> qw.isNull(EmployeeProject::getUnderProjectTime)
- .or().apply("DATE_FORMAT(under_project_time, '%Y-%m-%d') >= DATE_FORMAT(NOW(),'%Y-%m-%d')")));
执行SQL如下:
- SELECT
- *
- FROM
- employee_project
- WHERE
- state IS NOT NULL
- AND flag = 1
- AND (
- under_project_time IS NULL
- OR DATE_FORMAT(under_project_time, '%Y-%m-%d') >= '2022-07-27'
- );
示例四:
需求:根据传进来的年月字符串dateStr,查传入月的在职男员工数。dateStr = "2022-01"。
entry_time为入职时间,date类型
separated_time为离职时间,date类型
入职时间和离职时间为日期类型,需格式为年月的格式与传进来的dateStr进行比较筛选
查询逻辑:首先性别男,其次:①入职时间小于等于dateStr且未离职;②:入职时间小于等于dateStr,且离职时间大于等于dateStr。
- employeeMapper.selectList(new LambdaQueryWrapper<Employee>()
- .eq(Employee::getSex, 1)
- .and(qw ->
- qw.apply("date_format (entry_time,'%Y-%m') <= '" + dateStr + "' AND separated_time IS NULL" )
- .or()
- .apply("date_format (entry_time,'%Y-%m') <= '" + dateStr + "' AND date_format (separated_time,'%Y-%m') >= '" + dateStr + "'")));
执行SQL如下:
- SELECT
- *
- FROM
- employee
- WHERE
- sex = 1
- AND (
- date_format(entry_time, '%Y-%m') <= '2022-01'
- AND separated_time IS NULL
- OR date_format(entry_time, '%Y-%m') <= '2022-01'
- AND date_format(separated_time, '%Y-%m') >= '2022-01'
- );
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。