这会拉回昨天和今天的两个int值。我想从名为差异的第三列中的语句中减去两个结果:
SELECT (
SELECT COUNT(*)
FROM collectors_users
WHERE DATE(dateadded) = CURDATE() - INTERVAL 1 DAY
) AS yesterday, COUNT(*) AS today
FROM collectors_users
WHERE DATE(dateadded) = CURDATE()
答案 0 :(得分:1)
您需要重复表达式。 SQL(通常)不允许您在同一SELECT
中重用列别名。您可以将逻辑简化为:
SELECT SUM(DATE(dateadded) = CURDATE() - INTERVAL 1 DAY) AS yesterday,
SUM(DATE(dateadded) = CURDATE()) as today,
(SUM(DATE(dateadded) = CURDATE()) -
SUM(DATE(dateadded) = CURDATE() - INTERVAL 1 DAY)
) as diff
FROM collectors_users
WHERE dateadded >= CURDATE() - INTERVAL 1 DAY AND
dateadded < CURDATE() + INTERVAL 1 DAY;
请注意WHERE
子句的逻辑涵盖两天。此外,它不使用DATE()
。这将允许查询使用索引(如果可用)。