计算/检查mysql表中条目的第一个实例

  id          | user_id        |      date_tracked
---------------------------------------------
 1001         |  1             | 10-10-2013
 1002         |  2             | 10-10-2013
 1003         |  3             | 10-10-2013
 1004         |  1             | 10-11-2013
 1005         |  2             | 10-12-2013

I have a table similar to this, which tracks a user and a date. I need to find how many first-time entries for users occurred on a selected date. This table is going to hold a significant amount of data, which is why I'd like to rely on a query to process this instead of a bunch of PHP loops.

i.e. on 10-11-2013, user 1 visited but not their first time, so return 0 on 10-10-2013, user 1 and 2 visited for their first time, so return 2.

Obviously, using a simple query can count the number of entries on a specified date, but what methodology will allow me to only count if the user_id is not present on a row prior.

The table is ordered by date, meaning that a more recent date should never have a smaller id than an older date.

Any ideas?? Thanks!

Finding all "first time"-date, by user:

SELECT user_id, MIN(date_tracked) AS first_date
FROM table
GROUP BY user_id

Counting "first time", for each date:

SELECT t.first_date, COUNT(*) AS nb
FROM (SELECT user_id, MIN(date_tracked) AS first_date
FROM table
GROUP BY user_id) t
GROUP BY t.first_date

SELECT user_id, MIN(date_tracked) FROM table_name GROUP BY user_id

For counting as one, if the user visits multiple times in the first day, you can do it in two ways:

SELECT COUNT(distinct user_id)
FROM user t1
WHERE t1.date_tracked = '2013-10-12' 
AND NOT EXISTS (
    SELECT 1
    FROM user t2
    WHERE t2.user_id = t1.user_id
      AND t2.date_tracked < t1.date_tracked
    );

SELECT COUNT(user_id)
FROM user t1
WHERE t1.date_tracked ='2013-10-12'
AND NOT EXISTS (
SELECT 1
  FROM user t2
  WHERE t2.user_id = t1.user_id
    AND t2.id < t1.id
);

I think i prefer the second, as it is much more cleaner by comparing ID's and not having to do the distinct.

sqlfiddle demo

By your tags I assume you want your answer in php as well. Just one query: shouldn't date 10-10-2013 return 3? Anyway you can try this:

<?php

$dbConnect = @mysqli_connect($host, $user, $pass)or die();

@mysqli_select_db($dbConnect, $dbname) or die();
$query = "SELECT id FROM tablename WHERE date_tracked = '$searchDate' AND (SELECT COUNT(id) FROM tablename WHERE date_tracked < '$searchDate')=0";
$queryResult = @mysqli_query($dbConnect, $query) or die();
$rowCount = mysqli_num_rows($queryResult);
echo $rowCount . "<br/>";

mysqli_close($dbConnect);

?>

In response to Filipe,

Maybe this would be more suitable?

SELECT COUNT(*)
FROM table t1
WHERE t1.date ='2013-8-27'
AND NOT EXISTS (
SELECT 1
FROM table t2
WHERE t2.user_id = t1.user_id
  AND t2.id < t1.id
);