如何将一个复杂的mysql结果集,再筛选一次

时间:2024-05-21 11:56:09

通过下面的极其复杂的sql语句,如下

SELECT d.id AS uid,(SELECT paystudate_id FROM erp_demand_meter as b WHERE demand_id = d.id ORDER BY addtime DESC LIMIT 1) as pp, 
(SELECT uerdates FROM erp_demand_meter as b WHERE demand_id = d.id and b.paystudate_id = 14 ORDER BY addtime DESC LIMIT 1) as uerdat, 
(SELECT plan_time FROM erp_demand_meter AS b where Demand_id = d.id ORDER BY addtime DESC limit 1) AS plan_time, 
(SELECT addtime FROM erp_demand_meter WHERE Demand_id = d.id ORDER BY addtime DESC LIMIT 1) AS time ,
d.exec_name,d.paytime,d.paystudate,d.facttime,d.Demand_type_id,d. NAME,d.pid,d.addtime,d.company_type,d.demand_desc,d.pername,d.Demand_file_id, DATE_FORMAT(d.endtime, '%Y-%m-%d') AS edtime,d.state,d.perid,d.demand_level,d.demand_file,t.type_name,t.company_id,t.id 
FROM erp_demand d LEFT JOIN erp_demand_type t ON d.demand_type_id = t.id 
where d.paystudate = 0 and demand_type_id = 1 

ORDER BY d.update_time desc,uid desc limit 0,20


我们得到了一个多集合的结果集,我们这次的任务是pp为NULL和0的筛选出来

如何将一个复杂的mysql结果集,再筛选一次


用到:

(1)IFNULL(expr1,expr2)的用法:

假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1; 

(2)用select * from (结果集)as result  where IFNULL(result.pp,0) = 0 【可以找出null,0】


如下:

select * from
(SELECT d.id AS uid,(SELECT paystudate_id FROM erp_demand_meter as b WHERE demand_id = d.id ORDER BY addtime DESC LIMIT 1) as pp, 
(SELECT uerdates FROM erp_demand_meter as b WHERE demand_id = d.id and b.paystudate_id = 14 ORDER BY addtime DESC LIMIT 1) as uerdat, 
(SELECT plan_time FROM erp_demand_meter AS b where Demand_id = d.id ORDER BY addtime DESC limit 1) AS plan_time, 
(SELECT addtime FROM erp_demand_meter WHERE Demand_id = d.id ORDER BY addtime DESC LIMIT 1) AS time ,
d.exec_name,d.paytime,d.paystudate,d.facttime,d.Demand_type_id,d. NAME,d.pid,d.addtime,d.company_type,d.demand_desc,d.pername,d.Demand_file_id, DATE_FORMAT(d.endtime, '%Y-%m-%d') AS edtime,d.state,d.perid,d.demand_level,d.demand_file,t.type_name,t.company_id,t.id 
FROM erp_demand d LEFT JOIN erp_demand_type t ON d.demand_type_id = t.id 
where d.paystudate = 0

ORDER BY d.update_time desc,uid desc)a where IFNULL(a.pp,0) = 0


现在筛选出来了

如何将一个复杂的mysql结果集,再筛选一次