2016-09-21 113 views
0

這會拉回昨天和今天的兩個int值。我想從第三欄中的差異中減去聲明中的兩個結果:如何從該語句中的SELECT語句中減去兩個結果?

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() 

回答

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()。這將允許查詢使用索引(如果可用)。