目录
一、前言
业务描述
二、解决方法
2.1、用having去查询别名字段
2.2嵌套查询
在日常开发中我们根据工作需求来编写sql, 在开发中遇到一个利用不是表中字段作为条件进行查询, 因为困惑了我很久 , 今天来记录一下。
我的业务是三表联查,其中"sign" 是 notice_receive_record 表中 "notice_management_id" 是否为空用case when 来判断返回0 或者1 (不为空是1,反之则是 0)然后赋值到sign别名上
问题:在where 子句中sign如何作为查询条件去查询数据呢
看sql:
SELECT
nm.notice_name,
nm.id,
nm.notice_date,
nm.notice_party_org_name,
nm.notice_type,
nm.notice_status,
nrpo.party_org_name,
nrr.received_time,
nrr.notice_management_id,
nrpo.party_org_id,
( CASE WHEN nrr.notice_management_id IS NOT NULL THEN 0 ELSE 1 END ) AS sign
FROM
notice_management nm
LEFT JOIN notice_receive_party_org nrpo ON nm.id = nrpo.notice_management_id
LEFT JOIN notice_receive_record nrr ON nm.id = nrr.notice_management_id
适用于纯sql查询
看sql:
SELECT
nm.notice_name,
nm.id,
nm.notice_date,
nm.notice_party_org_name,
nm.notice_type,
nm.notice_status,
nrpo.party_org_name,
nrr.received_time,
nrr.notice_management_id,
nrpo.party_org_id,
( CASE WHEN nrr.notice_management_id IS NOT NULL THEN 0 ELSE 1 END ) AS sign
FROM
notice_management nm
LEFT JOIN notice_receive_party_org nrpo ON nm.id = nrpo.notice_management_id
LEFT JOIN notice_receive_record nrr ON nm.id = nrr.notice_management_id
WHERE
nm.notice_status=2
and nm.deleted=0
having sign like "%%"
看结果;
疑惑:having条件不是需要跟在group by 之后吗,这个希望大家能讨论一下
误区:在mabatis-plus中作为wapper条件查询是不行的
报错:Unknown column 'sign' in 'where clause'
这个是可以的 纯sql 和 mybatis-plus 查询wapper
看sql:
SELECT
*
FROM
(
SELECT
nm.notice_name,
nm.id,
nm.notice_date,
nm.notice_party_org_name,
nm.notice_type,
nm.notice_status,
nrpo.party_org_name,
nrpo.party_org_id,
( CASE WHEN nrr.notice_management_id IS NOT NULL THEN 0 ELSE 1 END ) AS sign
FROM
notice_management nm
LEFT JOIN notice_receive_party_org nrpo ON nm.id = nrpo.notice_management_id
LEFT JOIN notice_receive_record nrr ON nm.id = nrr.notice_management_id
WHERE
nm.notice_status = 2
AND nm.deleted = 0
) a
WHERE
a.sign LIKE "%%"
看结果