2014-01-13 121 views
3

如何從Last_updated大於「8個月」或(「date爲null」)和('Number_of_employees'小於等於的MySQL數據庫中獲取記錄到500)?MySQL獲取日期大於8個月的記錄

表的細節:

CREATE TABLE `companies` (
    `company_id` int(11) NOT NULL AUTO_INCREMENT, 
    `company_name` varchar(255) NOT NULL COMMENT, 
    `Number_of_employees` int(11) NOT NULL, 
    `Last_updated` datetime NOT NULL, 
    PRIMARY KEY (`company_id`), 
    UNIQUE KEY `Company_Name` (`company_name`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

這是我到目前爲止有:

SELECT * FROM companies WHERE Last_updated < (now() - interval 8 month); 

回答

1

試試這個:

SELECT * 
FROM companies 
WHERE Number_of_employeesless <= 500 AND 
    (Last_updated IS NULL OR DATE(Last_updated) >= (CURRENT_DATE() - INTERVAL 8 MONTH)); 

OR

SELECT * 
FROM companies 
WHERE Number_of_employeesless <= 500 AND 
    (Last_updated IS NULL OR DATE(Last_updated) >= DATE_SUB(CURRENT_DATE(), INTERVAL 8 MONTH)); 
+0

感謝Saharsh沙阿所以入住的回答讓我來試試,讓你知道:) – Max

+0

的'DATE(LAST_UPDATED)的使用'這裏是毫無意義的,更糟糕​​的是它會防止MySQL使用OP可能在Last_updated列上產生的任何索引,每次都會導致全面掃描。只是從條件中拋棄它。它應該只是'Last_updated> = DATE_SUB ...' – peterm

0

這應該做的伎倆:

SELECT * FROM companies 
WHERE last_updated > (now() - INTERVAL 8 MONTHS) 
AND number_of_employeesless <= 500 
相關問題