2015-02-05 56 views
0

我試圖對我的數據庫中不存在的數據進行連接,並且永遠不會更改。從mysql中的顯式表中選擇

我想做

SELECT val, campaign FROM values 
LEFT JOIN (SELECT campaign, start, end FROM (
    ('Spring 2104', '2014-05-01', '2014-08-01'), 
    ('Winter 2014', '2014-08-01', '2014-12-31') 
) as campaign_table ON (
    values.date > campaign_table.start AND 
    values.date < campaign_table.end 
) 

這可能嗎?我可以創建一個臨時表,但是對於我正在嘗試做的事情,實際上並不起作用。

+4

爲什麼你不試試看它是否有效? – Mehraban 2015-02-05 18:34:49

+0

今年呢? – Gervs 2015-02-05 18:56:42

回答

0

您可以使用union all來創建虛擬集。考慮到你的啞數據集中只有少數幾行,這是一個可行的解決方案。

SELECT val 
    ,campaign 
FROM 
VALUES 
LEFT JOIN (
    SELECT 'Spring 2104' campaign 
     ,'2014-05-01' start 
     ,'2014-08-01' [end] 

    UNION ALL 

    SELECT 'Winter 2014' 
     ,'2014-08-01' 
     ,'2014-12-31' 
    ) AS campaign_table ON 
VALUES.DATE > campaign_table.start 
    AND 
VALUES.DATE < campaign_table.[end] 
0

也許你需要這個執行所有查詢一次:

CREATE TABLE IF NOT EXISTS `tempo`(`campaign_name` VARCHAR(100), `from` DATE, `to` DATE); 
INSERT INTO tempo(campaign_name, `start`, `end`) VALUES ('Spring 2104', '2014-05-01', '2014-08-01'),('Winter 2014', '2014-08-01', '2014-12-31'); 
SELECT t1.val, t1.campaign, t2.campaign_name FROM `values` t1, `tempo` t2 WHERE t1.date BETWEEN t2.start AND t2.end; 
DROP TABLE `tempo`; 

你也可以做:CREATE TEMPORARY TABLE

試試!