MySQL WHERE子句优化:保留在店卡车并过滤超30天完工车辆
Fixing the Truck Data Query to Include Unfinished Vehicles
Let's sort out this query for you—here's how to adjust the WHERE clause to meet your exact needs: you want to retain two specific groups of trucks in your results:
- Trucks still in the shop (no release date set, meaning
Released_Date IS NULL) - Completed trucks that were released within the last 30 days (we'll exclude any finished trucks that left more than 30 days ago)
The Corrected Query
The original query only pulled recently completed trucks, missing the unfinished ones. We'll combine both valid conditions with a logical OR (wrapped in parentheses to avoid logic precedence issues):
SELECT Truck_ID, Recieved_Date, Released_Date FROM your_truck_table WHERE -- Keep all trucks that haven't been released yet Released_Date IS NULL OR -- Keep completed trucks released in the last 30 days Released_Date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
Breakdown of the Logic
Released_Date IS NULL: This captures every truck still in the shop, since they haven't been assigned a release date yet.Released_Date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY): This filters completed trucks to only those released in the past 30 days.CURDATE()gets today's date, andDATE_SUBsubtracts 30 days to set our cutoff point.
Quick Notes
- Don't forget to replace
your_truck_tablewith the actual name of your database table. - If
Released_Dateuses a datetime type (instead of a plain date), you can swapCURDATE()withNOW()if you need time-specific filtering, butCURDATE()is usually enough for day-based cutoffs.
内容的提问来源于stack exchange,提问作者SuspectT3
相关产品推荐
相关产品推荐

