0

I have 2 queries. Query 1:-

select mr.id,count(ml.id) as labor_cnt 
from mreq Mr 
join mlbr ml on Mr.id = ml.mrid 
where Mr.id in(1235,3355) 
group by Mr.id

Query 2:-

select mr.id,count(mm.id) as mtrial_cnt 
from mreq Mr join mmrm mm on Mr.id = mm.mrid 
where Mr.id in(1235,3355) 
group by Mr.id

Trying to use union all but won't work. Suggest any alternative to combine them.

1
  • what you call combine?.. how results look for both queries? Commented Jun 18, 2016 at 15:10

1 Answer 1

1

Since you're grouping by mr.id in both queries, I assume you want results something like:

 mr.id | labor_cnt | mtrial_cnt
--------------------------------
     1 |         5 |          3
     2 |      null |          6
     3 |         4 |          2
     4 |         3 |       null
...

If that's what you're looking for, then you can combine the queries with common table expressions. Something like:

WITH labor as (
  SELECT mr.id AS mrid, count(ml.id) AS labor_cnt
    FROM mreq mr JOIN mlbr ml ON mr.id = ml.mrid
    WHERE mr.id IN (1235, 3355)
  GROUP BY mr.id),

mtrial as (
  SELECT mr.id AS mrid, count(mm.id) AS mtrial_cnt
    FROM mreq mr JOIN mmrm mm ON mr.id = mm.mrid
    WHERE mr.id in (1235, 3355)
  GROUP BY mr.id)

SELECT COALESCE(l.mrid, m.mrid), l.labor_cnt, m.labor_cnt
  FROM labor l FULL OUTER JOIN mtrial m ON mrid
ORDER BY mrid;

Edited to add

It looks like you're using MySQL, and MySQL does not support common table expressions. MySQL does support subqueries, so this may work (note: I haven't verified the syntax, as I don't have a running MySQL instance available):

SELECT COALESCE(l.mrid, m.mrid), l.labor_cnt, m.labor_cnt
  FROM 
    (SELECT mr.id AS mrid, count(ml.id) AS labor_cnt
       FROM mreq mr JOIN mlbr ml ON mr.id = ml.mrid
       WHERE mr.id IN (1235, 3355)
     GROUP BY mr.id) AS labor

    FULL OUTER JOIN

    (SELECT mr.id AS mrid, count(mm.id) AS mtrial_cnt
       FROM mreq mr JOIN mmrm mm ON mr.id = mm.mrid
       WHERE mr.id in (1235, 3355)
     GROUP BY mr.id) AS mtrial

    ON mrid

ORDER BY mrid;
Sign up to request clarification or add additional context in comments.

4 Comments

Yes somethink like this I am looking for.Might that works for me!! Thanks.
Getting #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'labor as ( SELECT mr.id AS mrid, count(ml.id) AS labor_cnt FROM ' at line 1
You labeled this as postgresql, so I used syntax for postgres. I'm not sure what the equivalent syntax would be with mysql.
I've added an unverified MySQL example. In the future, please be more careful with your tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.