2013-02-20 84 views
0

我不確定它是否可能,但是我可以使用set vars來避免在以下查詢上重複日期範圍嗎?那麼我只會聲明TY和LY一次並在查詢中重用?在日期範圍之間的mysql變量避免重複

// ThisYear -- '2013-02-04 00:00:00' AND '2013-02-10 23:59:59' 
// LastYear -- '2012-02-06 00:00:00' AND '2013-02-12 23:59:59' 

SELECT 
    count(*) as total_num_bookings, 

    SUM(if(book_date BETWEEN '2013-02-04 00:00:00' AND '2013-02-10 23:59:59', 1, 0)) AS num_bookings_ty, 
    SUM(if(book_date BETWEEN '2012-02-06 00:00:00' AND '2012-02-12 23:59:59', 1, 0)) AS num_bookings_ly, 
    sj.pu_country 

FROM 
    pc_tech.sales_journal_default sj 

WHERE (book_date BETWEEN '2013-02-04 00:00:00' AND '2013-02-10 23:59:59') OR (book_date BETWEEN '2012-02-06 00:00:00' AND '2012-02-12 23:59:59') 
group by pu_country 
order by total_num_bookings DESC 
LIMIT 25; 

回答

1

是:

SET @ThisYear1='2013-02-04 00:00:00', @ThisYear2='2013-02-10 23:59:59' 
SET @LastYear1='2012-02-06 00:00:00', @LastYear2='2013-02-12 23:59:59' 

SELECT 
    count(*) as total_num_bookings, 

    SUM(if(book_date BETWEEN @ThisYear1 AND @ThisYear2, 1, 0)) AS num_bookings_ty, 
... 

編輯

或者使用準備好的語句:

SET @ThisYear="'2013-02-04 00:00:00' AND '2013-02-10 23:59:59'"; 
SET @LastYear="'2012-02-06 00:00:00' AND '2013-02-12 23:59:59'"; 

SET @sql = CONCAT("SELECT count(*) as total_num_bookings, SUM(if(book_date BETWEEN ", @ThisYear, ", 1, 0)) AS num_bookings_ty, ..."); 
PREPARE stmt from @sql; 
EXECUTE stmt; 
... 
DEALLOCATE PREPARE stmt; 
+0

它必須是4個變量?今年是兩年還是去年? – 2013-02-20 16:42:34

+0

@Robbo_UK - 你可以用準備好的語句來完成,如果那樣的話。看到我更新的答案。 – Raad 2013-02-20 17:11:15