SELECT
  t1.p01 as p01,
  t1.p02 as p02,
  t1.p04 as p04,
  t1.p06 as p06,
  concat(if(t1.ptax=100, '{message(255)} ', ''), que_tbls.p03, ' ', t1.p05) as p03,
  t1.remdate as remdate, 
  t1.remtime as remtime, 
  t1.remuser as remuser, 
  t1.remfdate as remfdate, 
  t1.remftime as remftime, 
  t1.remfuser as remfuser, 
  t1.remguc as remguc
FROM
(
         select p20.p01 as p01,
                if(locate('.', p20.p02)=0, p20.p02, substr(p20.p02, locate('.', p20.p02)+1,100)) as p02, 
                if(locate('.', p20.p02)=0, '', substr(p20.p02, 1, locate('.', p20.p02)-1)) as p06, 
                p20.p04 as p04,
                p20.p10 as p05, 
                p20.remdate as remdate, 
                p20.remtime as remtime, 
                p20.remuser as remuser, 
                p20.remfdate as remfdate, 
                p20.remftime as remftime, 
                p20.remfuser as remfuser, 
                p20.remguc as remguc, 
                if(p20.p03='***', 100, 0) as ptax 

         FROM p20
         WHERE p03='{p_q10reltb}'
            || (p03='***' && p01<>'{p_q10reltb}' && locate('.', p02)>0)

         UNION ALL

         select p20.p03 as p01,
                if(locate('.', p20.p04)=0, p20.p04, substr(p20.p04, locate('.', p20.p04)+1,100)) as p02, 
                if(locate('.', p20.p04)=0, '', substr(p20.p04, 1, locate('.', p20.p04)-1)) as p06, 
                p20.p02 as p04,
                p20.p10 as p05, 
                p20.remdate as remdate, 
                p20.remtime as remtime, 
                p20.remuser as remuser, 
                p20.remfdate as remfdate, 
                p20.remftime as remftime, 
                p20.remfuser as remfuser,
                p20.remguc as remguc,
                if(p20.p01='***', 100, 0) as ptax 
         FROM p20
         WHERE p01='{p_q10reltb}'
            || (p01='***' && p03<>'{p_q10reltb}' && locate('.', p04)>0)
) as t1, que_tbls
WHERE t1.p01=que_tbls.p01
ORDER BY t1.ptax, que_tbls.p03;
