简体   繁体   中英

Select distinct column value from date range

I created a sqlfiddle that outlines what I'm trying to do:

http://sqlfiddle.com/#!9/41f3c/2

Basically, I need to search for unique posts in a table that contains meta information. The meta in this instance is a series of dates that represent exclusions (think of a booking system for a hotel).

I pass in a start and end date. I want to find post_id that does not contain a date that falls in the range. I'm close, but can't quite figure it out.

SELECT DISTINCT post_id 
FROM wp_facetwp_index
WHERE facet_name = 'date_range'
AND facet_value NOT BETWEEN '$start_date' AND '$end_date'

This works if the only excluded dates in the table are in the range, but if some are out of the range, I still get the post_id.

Thanks for looking.

Do not forget, in SQL, the filters (where clause, etc.) are applied on a RECORD basis. Each record is evaluated independantly from the others.

So, since

(1, 511, 'date_range', 'cf/excluded_dates', '2015-07-31', '2015-07-31')

validates your condition, 511 is returned.

Since post_id is not unique, you need to proceed with a exclusion on SETS, as opposed to an exclusion on RECORDS which you're doing right now.

Here is the solution (adjusted fiddle here: http://sqlfiddle.com/#!9/41f3c/7 )

SELECT DISTINCT i1.`post_id` 
FROM `wp_facetwp_index` i1
WHERE i1.`facet_name` = 'date_range'
AND NOT EXISTS (
    SELECT 1
    FROM `wp_facetwp_index` i2
    WHERE 
        i2.`facet_value` BETWEEN '$start_date' AND '$end_date'
    AND i2.`facet_name` = 'date_range'
    AND i2.`post_id` = i1.`post_id`
)

The subquery right after EXISTS ( is a subset of rows. It will be evaluated negatively by NOT EXISTS based on the junction i2.post_id = i1.post_id . This is a negative intersection.

Working on exluding records does not work if the tuple you need to indentify is not unique.

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