Home >Database >Mysql Tutorial >How to Correctly Find Players on a Team Within a Specific Year Range in PostgreSQL?
Finding Overlapping Date Ranges in PostgreSQL
You've provided a query that attempts to find all players who were on a specific team in a given year, but it's not working correctly. Let's address the issues you're facing and provide an alternative solution for finding overlapping date ranges.
Problems with the Original Query:
Correct Query:
To find all players of a given team who joined before 2010 and didn't leave before 2009, you can use the following query:
SELECT DISTINCT p.* FROM team AS t JOIN contract AS c ON t.name_team = c.name_team JOIN player AS p ON c.name_player = p.name_player WHERE t.name_team = ? AND c.date_join < '2010-01-01' AND c.date_leave >= '2009-01-01';
Additional Considerations:
AND (c.date_leave >= '2009-01-01' OR c.date_leave IS NULL)
Using the OVERLAPS Operator:
PostgreSQL also provides the OVERLAPS operator, which can be used to find overlapping ranges. The following query uses OVERLAPS to find players who overlapped with the range '2009-01-01', '2010-01-01':
SELECT DISTINCT name_player FROM contract WHERE name_team = ? AND (date_join, COALESCE(date_leave, CURRENT_DATE)) OVERLAPS ('2009-01-01', '2010-01-01');
Using a Range Type:
In PostgreSQL 9.2 or later, you can use a range type to represent date ranges. This provides better performance and allows for easier index support.
CREATE TYPE date_range AS RANGE (date, date); CREATE INDEX mv_stock_dr_idx ON mv_stock USING gist (daterange(date_join, date_leave)); SELECT DISTINCT name_player FROM contract WHERE name_team = ? AND daterange(date_join, date_leave) &&& daterange('[2009-01-01,2010-01-01)'); -- upper bound excluded
The above is the detailed content of How to Correctly Find Players on a Team Within a Specific Year Range in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!