Reputation: 175
I have about 5 tables with common field “userid” I want to count distinct userids across all these tables. Certain user ids may occur in about 2 of these tables. But I want to count the UNION of distinct user ids in the 5 tables together. I am able to count distinct userids in one table with the ff code. I want to be able count from all tables.
//just count the nuber of distict userids in table1
$query2 = ("SELECT COUNT(DISTINCT userid) FROM table1");
$result2 = mysql_query($query2) or die(mysql_error());
$row2 = mysql_fetch_row($result2);
echo "Number of users in table 1 = ".$row2[0] ."<br />";
**Table 1**
Id userid name adresss
**Table 2**
Id Title Sex userid
**Table 3**
Id userid amount
**Table 4**
Id price promotion userid productid
**Table 5**
Id userid category tax weight
Upvotes: 3
Views: 1903
Reputation: 58431
Use a UNION
A standard UNION
, in contrast with a UNION ALL
, will remove duplicate values from the resultset. Your statement would look like
SELECT COUNT(*)
FROM (
SELECT UserID FROM Table1
UNION SELECT UserID FROM Table2
UNION SELECT UserID FROM Table3
UNION SELECT UserID FROM Table4
UNION SELECT UserID FROM Table5
) AS UserIDs
the UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
Upvotes: 7