2012-04-13 73 views
0

我可以得到一些幫助來清理以下查詢並可能將其轉換爲連接。將查詢轉換爲加入

SELECT pd.id, pd.title, pd.vacation_type_ids, pd.auto_vacation_theme 
FROM property_details pd 
WHERE pd.company_id =247 
AND pd.status = "active" 
AND pd.id NOT 
IN (
    SELECT d.property_id 
    FROM property_discount d 
    WHERE (
    (
    d.start_date <= CAST( "2012-04-15" AS DATE) 
    AND d.end_date >= CAST( "2012-04-15" AS DATE) 
    AND d.start_date <= CAST( "2012-04-17" AS DATE) 
    AND d.end_date >= CAST( "2012-04-17" AS DATE) 
    ) 
    OR (
    d.start_date >= CAST( "2012-04-15" AS DATE) 
    AND d.start_date <= CAST( "2012-04-17" AS DATE) 
    ) 
    OR (
    d.end_date >= CAST( "2012-04-15" AS DATE) 
    AND d.end_date <= CAST( "2012-04-17" AS DATE) 
    ) 
) 
) 

我沒有與MySQL的專家很抱歉,如果我已經做錯了什麼

+0

正如tombom解釋的那樣,您的WHERE子句是一團糟。這個怎麼樣。而不是你不想要的東西,你試圖在折扣中找到什麼被排除在外。看起來,你希望任何發現STARTED至少爲4/15的工作,並且是在4/17或之前完成的。如果是這樣,這些是您想要從結果中「忽略」的屬性。這是否準確? – DRapp 2012-04-13 13:28:25

回答

0

這整個事情是沒有意義的我。

WHERE (
(
d.start_date <= CAST( "2012-04-15" AS DATE) 
AND d.end_date >= CAST( "2012-04-15" AS DATE) 
AND d.start_date <= CAST( "2012-04-17" AS DATE) 
AND d.end_date >= CAST( "2012-04-17" AS DATE) 
) 
OR (
d.start_date >= CAST( "2012-04-15" AS DATE) 
AND d.start_date <= CAST( "2012-04-17" AS DATE) 
) 
OR (
d.end_date >= CAST( "2012-04-15" AS DATE) 
AND d.end_date <= CAST( "2012-04-17" AS DATE) 
) 
) 

第一個塊可以簡化爲基本start_date <= '2012-04-17' AND end_date >= '2012-04-17'。這個案例由第二個和第三個塊處理,其基本上分別是start_date BETWEEN '2012-04-15' AND '2012-04-17'end_date BETWEEN '2012-04-15' AND '2012-04-17'

你真的想要一個OR在這個之間嗎,或者是一個AND

您沒有提供關於您的數據庫設計的信息,所以我只能猜測,如果這兩個表之間的以下連接是正確的。

SELECT pd.id, pd.title, pd.vacation_type_ids, pd.auto_vacation_theme 
FROM property_details pd 
INNER JOIN property_discount d ON pd.id = d.property_id 
WHERE pd.company_id =247 
AND pd.status = 'active' 
(
d.start_date BETWEEN '2012-04-15' AND '2012-04-17' /*this is right when start_date is of type date, when it's datetime or timestamp you better write '2012-04-17 23:59:59', otherwise '2012-04-17 00:00:00' is assumed, which is basically not considering this date*/ 
OR 
d.end_date BETWEEN '2012-04-15' AND '2012-04-17' 
)