2017-11-10 124 views
0

我試圖選擇公司和日期不同的數據類型/ ID的數據表中的數據。選擇大表中某些ID不存在於同一列中的數據。加快查詢

換句話說,我想company_id, dates_id, daily_val其中wh_calc_id = 344如果相同company_id/dates_id組合不存在其中wh_calc_id = 368

我鬆散下面這個例子: Select rows which are not present in other table

這些都是我的兩次嘗試吧:

嘗試1:

SELECT distinct on (company_id, dates_id) company_id, dates_id, daily_val 
FROM daily_data d1 
WHERE NOT EXISTS (
         SELECT 1    
         FROM daily_data d2 
         WHERE d1.company_id = d2.company_id 
           and d1.dates_id = d2.dates_id 
           and d1.wh_calc_id = 368 
           and d2.wh_calc_id = 368 
        ) 
    and d1.wh_calc_id = 344 

問題: 這是超級慢:15分鐘

嘗試2:[刪除]

All in one的(巨)表: COMPANY_ID INT(索引), dates_id INT(索引), wh_calc_id INT(索引), daily_val數字

我打開添加索引,這將有助於速度東西了,但是什麼索引?

Postgres的10

PS - 我有他們完成之前殺了兩個查詢,所以我真的不知道他們是否正確寫入。希望我的描述有所幫助。

+1

我會在這種情況下使用左連接:select distinct on(company_id,dates_id)company_id,dates_id,daily_val FROM daily_data d1 LEFT JOIN daily_data d2 ON d1.company_id = d2.company_id和d1.dates_id = d2.dates_id和d1.wh_calc_id = 368和d2.wh_calc_id = 368 WHERE d1.wh_calc_id = 344 AND d2.company_id IS NULL;並在要使用的列上創建索引:在表daily_data(company_id,dates_id,wh_calc_id)上創建索引; –

回答

0

這不會是我想要我認爲:

SELECT 
    d1.* 
from 
    daily_data d1 
LEFT JOIN 
    daily_data d2 
ON 
    d1.company_id  = d2.company_id 
    AND d1.dates_id = d2.dates_id 
    AND d2.wh_calc_id = 368 
    AND d1.wh_calc_id = 344 

where 
    and d1.wh_calc_id = 344 
    and d2.wh_calc_id is null 
0

我會用左手做加盟這樣:

SELECT distinct on (company_id, dates_id) company_id, dates_id, daily_val FROM daily_data d1 LEFT JOIN daily_data d2 ON d1.company_id = d2.company_id and d1.dates_id = d2.dates_id and d1.wh_calc_id = 368 and d2.wh_calc_id = 368 WHERE d1.wh_calc_id = 344 AND d2.company_id IS NULL;

,並創造超過列的索引使用:

Create index on table daily_data (company_id, dates_id, wh_calc_id);

+0

事實證明,沒有做我想要的。 – mountainclimber

相關問題