简体   繁体   中英

What's wrong with sql query?

What I need to do is, to return today's registered user's count and activated users count (for today) My query looks like that.

SELECT
    Count(u1.id) AS `registered`,
    Count(u2.id) AS `active`
FROM
    USER u1,
    USER u2
WHERE
    u1.registeredAt = CURDATE()
AND u2.active = 1;

What am I doing wrong that it returns 0 value for both?

Your question is a little unclear with respect to the actual query. First, I'll start with the date. CURDATE() returns the date portion of whatever current date/time is, no problem. However, you are asking for "RegisteredAt" = curdate(). Is the RegisteredAt stored as just a date, or full date/time. If full date time, you should probably account via

where u1.RegisteredAt >= CURDATE()

so it gets everything since the beginning of the day, and since nobody should have a registeredAt date GREATER than today, you do not need to explicitly add AND u1.registeredAt < tomorrow.

Now, your consideration of "Active". If this too is for the current date only, then adjust this to a IF() or case/when based on your preference and you only need the users table ONCE in the query

SELECT
    Count(u1.id) AS `registered`,
    sum( if( u1.active = 1, 1, 0 )) as ActiveToday
FROM
    USER u1
WHERE
    u1.registeredAt >= CURDATE()

The problem in your code may be cross joining. Solution:

SELECT (SELECT count(id) FROM User WHERE registeredAt = CURDATE()) AS `registered`,
    (SELECT count(id) FROM User WHERE active = 1) AS `active`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM