3

I am attempting to query a MySQL database with PHP to count the total number of entries without duplicates.

EXAMPLE
N111US
N111US
N123US
N345US
A6-EWD
A7-EEE
B-18701
N123US
N345AA

I wish to have the total number of the unique entries, and I cannot begin to see where to start with the SQL query, that is, Total Returned: 7

1
  • 2
    add in the end of query group by coloumn Commented Apr 15, 2013 at 19:59

2 Answers 2

20

This DISTINCT in this query:

SELECT COUNT(DISTINCT `column`) AS `cnt` FROM `table`;

will eliminate duplicates.

Then, from php, fetch the cnt column value the way you would do for any other regular query.

Sign up to request clarification or add additional context in comments.

2 Comments

This solution works but count distinct is an abomination in terms of performance. Array_unique in php7 is a blast.
I'll just add that query duration for me using COUNT(DISTINCT xxx, yyy) was basically the same as for a query that only used DISTINCT to show all entries. Actually the COUNT(DISTINCT xxx, yyy) on was a tiny bit faster (.312 sec vs .375 sec)
1

I like the SQL answers posted above. They're efficient and performed on the query, itself. But if you have already read the items from the database into an array, you can use PHP's array_unique--then get a count of that result into an array with count. For example:

<?php
$input = array("a" => "dog", "cat", "b" => "cat", "dog", "mouse");
$result = array_unique($input);
$uniqueCount = count($result);
?>

Hope this helps. :)

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.