如何从昨天开始只选择我的sql数据库?这是我的代码:
SELECT *, COUNT(visitors.usr_id) as usr_count FROM user, visitors WHERE visitors.usr_id = $usr_id GROUP BY $usr_id ORDER BY usr_count LIMIT 1
我的数据库名称是timein以及它输入INSERT完成日期和时间的方式。这是代码:
Database column : timein
Database insert looks like : 2012-9-6 9:11:35
基本上我希望能够从昨天开始SELECT和COUNT。我怎样才能从昨天开始从我的sql数据库中选择COUNT?
答案 0 :(得分:1)
您的查询没有意义。您正在user
和visitors
之间进行交叉联接,然后仅对访问者进行过滤。我怀疑你想要的东西:
SELECT *, COUNT(visitors.usr_id) as usr_count
FROM user join
visitors
on visitors.usr_id = user.usr_id
WHERE user.usr_id = $usr_id
GROUP BY $usr_id
ORDER BY usr_count
LIMIT 1;
获取昨天数据的where
子句将是:
WHERE date(timein) = date(NOW() - INTERVAL 1 DAY)
或者,如果您在timein
上有索引:
WHERE timein >= date(NOW() - INTERVAL 1 DAY) and timein < date(NOW())
答案 1 :(得分:0)
试试这个为昨天添加条件timein <= NOW() - INTERVAL 1 DAY , timein >= NOW() - INTERVAL 2 DAY;
SELECT *, COUNT(visitors.usr_id) as usr_count
FROM user, visitors
WHERE visitors.usr_id = $usr_id
AND timein <= NOW() - INTERVAL 1 DAY
AND timein >= NOW() - INTERVAL 2 DAY
GROUP BY $usr_id
ORDER BY usr_count
LIMIT 1
或者您可以使用BETWEEN
SELECT *, COUNT(visitors.usr_id) as usr_count
FROM user, visitors
WHERE visitors.usr_id = $usr_id
AND timein BETWEEN NOW() - INTERVAL 1 DAY AND NOW() - INTERVAL 2 DAY;
GROUP BY $usr_id
ORDER BY usr_count
LIMIT 1