1

I have a Database with two tables:

subscriber_mm
uid_local   | uid_foreign   | uid_partner   
7           |2              |0      
7           |4              |0      
2           |1              |0  
2           |2              |0  
5           |1              |0      
5           |3              |0

partner_mm
uid_local   | uid_foreign   | uid_partner 
7           |1              |1

My goal is to count the total number of rows by uid_local from both tables example:

count both tables by uid_local = 7 

result: 3

example:

count both tables by uid_local = 2 

result: 2

This is my solution (not the best) without the WHERE statement

SELECT sum(
ROWS ) AS total_rows
FROM (
SELECT count( * ) AS ROWS
FROM partner_mm
UNION ALL
SELECT count( * ) AS ROWS
FROM subscriber_mm
) AS u

how can i implement the WHERE statement?

1
  • - PHP-Version: 4.4.9 - Server Version: 5.5.28 - ENGINE=MyISAM DEFAULT CHARSET=utf8; Commented Feb 12, 2014 at 11:10

3 Answers 3

1

Here pass a value instead of 2 for your query :

select sum(total_count ) as total_count  from 
(select count(*) as total_count from subscriber_mm s where s.uid_local=2
union all 
select count(*) as total_count from partner_mm m where m.uid_local=2) as a 

or

 select a.uid_local,sum(total_count ) as total_count  from 
    (select s.uid_local as uid_local, count(*) as total_count from subscriber_mm s group by s.uid_local
    union all 
    select m.uid_local as uid_local, count(*) as total_count from partner_mm m group by m.uid_local) as a  
group by a.uid_local
Sign up to request clarification or add additional context in comments.

Comments

0

Please Try it

    select  uid_local,uid_foreign,uid_partner from subscriber_mm
union
select uid_local,uid_foreign,uid_partner from partner_mm

You can use Union For sum two table rows

Comments

0

No need of doing SUM since you need only to count the total number of rows returned from both tables for particular uid_local. The total rows can be obtained by using UNION ALL operator which clubs the resultset returned from both the tables WITHOUT removing the repeated records

Select count(*) as Result From

(

Select * from subscriber_mm
where uid_local=7
union all
Select * from subscriber_mm
where uid_local=7

)as tmp

Comments

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.