简体   繁体   中英

SELECT a date that is greater than current date

I have a MySQL database table where a single cell contains multiple dates and I am wanting to SELECT all rows that contain a cell where one or more of the dates is greater than todays date is this possible? (using PHP)

Sure:

select * from MyTable where MyDate > Now()

How does your single field contain multiple dates? Maybe you should consider a separate table for this instead.

如果该字段是DATEDATETIME ,则可以使用

SELECT * FROM table WHERE datefield > NOW()

A "single cell contains multiple dates" .. is the crux of the problem. Here are three options.

Normalize/fix the schema

Start with an adequately normalized schema - in particular, any column/"cell" can have at most one date (or piece of information). This may or may not require introducing another table depending upon the role of the information.

This approach is scalable and works within the RDMBS/RA design and, if done, the other queries presented would "just work".

(This is by far the overall best option and should be done if at all possible. Proper normalization should also guide further schema development to mitigate such issues in the future.)

Create a normalized view

Create a normalized view of the denormalized table (or such a nomalizing query) that can be JOIN ed. Then use one the various suggested answers (that work on a normalized schema) .. albeit at an extreme disadvantage of not being able to utilize indices.

This is terribly messy, but it can be done. See SELECT de-normalized columns into separate records? for an example. (Note the synthesized row relationship here, although some [non MySQL] databases also support table-valued functions and cross applications of such.)

This approach does not scale because it cannot use indices.

Filter in client (PHP)

Fetch every row. Loop and use explode , etc, as appropriate.

This approach does not scale due to lack of indices and requiring all the data is fetched locally.


While finding equal values in denormalized columns can be done with various hacks (eg FIND_IN_SET ), finding relative (ie larger/smaller) values is not possible with the same techniques. The solution that works in both cases is to fix the underlying schema.

如果仅在DATE而不是DATETIME ,则可以使用CURDATE()代替NOW()

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