如何將一個複雜的mysql結果集,再篩選一次

阿寶123發表於2018-03-01

通過下面的極其複雜的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的篩選出來


用到:

(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


現在篩選出來了








相關文章