# Sql count if user\_id exists in 2 tables

**URL:** <https://www.ruby-forum.com/t/sql-count-if-user-id-exists-in-2-tables/145039>\
**Category:** Rails\
**Created:** [August 5, 2008, 3:09pm UTC](https://www.ruby-forum.com/t/sql-count-if-user-id-exists-in-2-tables/145039 "2008-08-05T15:09:11Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![srinathbtech](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/7bcc69/32.png) [@srinathbtech](https://www.ruby-forum.com/u/srinathbtech)\
**Post date:** [August 5, 2008, 3:09pm UTC](https://www.ruby-forum.com/t/sql-count-if-user-id-exists-in-2-tables/145039/1 "2008-08-05T15:09:11Z")

</div>

Hi,

i want a query where there were two tables called

nutrition\_trackers fitness\_trackers  
id user\_id updated\_at id user\_id workout\_day  
1 2 2008-02-20 1 2 2008-02-23  
2 2 2008-03-23 2 1 2008-02-23  
3 1 2008-02-20 3 1 2008-03-20  
4 1 2008-03-10 4 1 2008-04-30  
5 1 2008-04-15  
and now i want the count of users that were present in both tables.

i am using the sql like this but getting count of users if exists in any  
1 table though

SELECT count(distinct fitness\_trackers.user\_id) AS count\_all,  
DATE\_FORMAT(workout\_day, ‘%b %Y’) AS date\_format FROM fitness\_trackers  
join nutrition\_trackers ON fitness\_trackers.user\_id =  
nutrition\_trackers.user\_id WHERE (fitness\_trackers.workout\_day BETWEEN  
‘2008-01-01’ and ‘2008-07-31’ and nutrition\_trackers.updated\_at BETWEEN  
‘2008-01-03’ and ‘2008-07-31’) GROUP BY DATE\_FORMAT(workout\_day, ‘%b  
%Y’)

o/p =\> count\_all date\_format  
2 Feb 2008  
2 Mar 2008  
1 Apr 2008

But i want to get output like this  
o/p =\> count\_all date\_format  
2 Feb 2008  
1 Mar 2008  
1 Apr 2008

as there was no user with id 2 in fitness\_trackers in March 2008 where  
id 1 was present in both tables in March should get count 1 here,  
i want to get count like this but my sql was retrieving those who were  
present in atleat 1 table too, can we refine my sql to get the perfect  
count for particular months

any help ??

thanks
