简体   繁体   中英

Proper MYSQL syntax for timestamp comparison and distinct results with certain exclusions

Sorry for asking, but I've never had to do such a complex MYSQL query before and I don't actually know what to google search in order to get the answer.

I have a poorly crafted database with a table of appointments of pregnant women that includes the day they came and the number of weeks pregnant they were at that time. I'm trying to select each one that should be 30 weeks right now but that doesn't already have a separate entry after 25 weeks pregnancy. I use the phone number to uniquely identify each person.

Since I really don't know how to formulate this query, this is the best I've come up with.

SELECT * FROM patientlist WHERE 
    UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`) - `weekspreg`*604800) > 29*604800 

AND 

    UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`)- `weekspreg`*604800) <= 30*604800 

AND
 /* a subquery that keeps out results where the phone number would show up elsewhere in the table for a woman with more than 25 weeks of pregnancy. */

There has to be a better solution than separately querying each of the results from the date range by phone number to see if the weekspreg is more than 25.

Thank you in advance for any help or direction.

Your entire WHERE is incorrect. A query can only have ONE where clause. You join multiple conditions with and and or , not and where :

WHERE foo AND bar  // correct
WHERE foo AND WHERE bar // syntax error

Check out the MySQL Date and Time Functions . For example, I'm not entirely certain what that last WHERE clause is trying to do, but I believe the first portion could be rewritten as something like:

SELECT * 
FROM patientlist
WHERE `date` - interval `weekspreg` week
   between now() - interval 29 week 
   and now() - interval 30 week

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM