Nicholas
Nicholas

Reputation: 13

Need to find number of new unique ID numbers in a MySQL table

I have an iPhone app out there that "calls home" to my server every time a user uses it. On my server, I create a row in a MySQL table each time with the unique ID (similar to a serial number) aka UDID for the device, IP address, and other data.

Table ClientLog columns: Time, UDID, etc, etc.

What I'd like to know is the number of new devices (new unique UDIDs) on a given date. I.e. how many UDIDs were added to the table on a given date that don't appear before that date? Put plainly, this is the number of new users I gained that day.

This is close, I think, but I'm not 100% there and not sure it's what I want...

SELECT distinct UDID
FROM ClientLog a
WHERE NOT EXISTS (
    SELECT * 
    FROM ClientLog b 
    WHERE a.UDID = b.UDID AND b.Time <= '2010-04-05 00:00:00'
)

I think the number of rows returned is the new unique users after the given date, but I'm not sure. And I want to add to the statement to limit it to a date range (specify an upper bound as well).

Upvotes: 1

Views: 522

Answers (1)

Can Berk G&#252;der
Can Berk G&#252;der

Reputation: 113310

Your query seems correct, and you can add bounds like this:

SELECT DISTINCT UDID FROM ClientLog a WHERE a.Time >= '2010-04-05 00:00:00'
                                        AND a.Time <  '2010-04-06 00:00:00'

AND NOT EXISTS(SELECT * FROM ClientLog b WHERE a.UDID = b.UDID
                                           AND b.Time < '2010-04-05 00:00:00');

UPDATE: another method that comes to mind is below, but I believe it's slower:

SELECT DISTINCT UDID FROM ClientLog a WHERE a.Time >= '2010-04-05 00:00:00'
                                        AND a.Time <  '2010-04-06 00:00:00'
                                        AND a.UDID <> ALL
(SELECT DISTINCT udid FROM ClientLog b where b.Time < '2010-04-05 00:00:00');

UPDATE 2: Of course, if you're only interested in the number of new UDIDs, then this would be the best solution:

SELECT COUNT(DISTINCT UDID) FROM ClientLog WHERE Time < '2010-04-05 00:00:00';
SELECT COUNT(DISTINCT UDID) FROM ClientLog WHERE Time < '2010-04-06 00:00:00';

Then take the difference in your code (there might be a way to do it in MySQL, but I'm not a MySQL expert).

Upvotes: 1

Related Questions