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 专家,如果我做错了什么,我很抱歉

4

1 回答 1

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'
)
于 2012-04-13T13:15:15.653 回答