Jump to content

Counting Select Distincts


QuePID

Recommended Posts

Hi,

 

I have a database with roughly 73k rows (records).  I am using a query string such as:

SELECT DISTINCT Column FROM databasename

 

I am then using mysql_num_rows($results) to count the number of distinct rows.  This method works, but it is slow.

 

Is there a faster way of doing this perhaps internal to the mysql without having to send the entire results to the PHP when I only need a count?

Link to comment
Share on other sites

select count( distinct column ) from databasename

 

When I echo the results of your query string I get "Resource id #6", and when I use mysql_num_rows($results) I get a value of 1 which isn't correct (should be 224).  What is the type of data returned in the results of the query?

Link to comment
Share on other sites

Using fenway's query with PHP code:

<?php
$results = mysql_query("SELECT COUNT(DISTINCT column) AS myCount FROM table");
$values = mysql_fetch_assoc($results);

echo $values['myCount'];
?>

 

Worked like a charm, and was quite fast.  How would I do similar for a count of all records within the table?

Link to comment
Share on other sites

Worked like a charm, and was quite fast.  How would I do similar for a count of all records within the table?

 

<?php
$results = mysql_query("SELECT COUNT(*) AS totalCount FROM table");
$values = mysql_fetch_assoc($results);

echo $values['totalCount'];
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.