Question

I have a table (temps) structure like this: How can I run a query that will iterate through all the rows and give me back for each row what other CITIES (name) have the temperature that falls within the SAME range ( current_low >= low AND current_high <= high) as the current ROW's low and high temperature.

+----+---------+------+------+---------------------+
| id | name    | low  | high | day                 |
+----+---------+------+------+---------------------+
|  1 | NYC     |   50 |   59 | 2012-01-01 00:00:00 |
|  2 | NYC     |   53 |   65 | 2012-01-02 00:00:00 |
|  3 | NYC     |   40 |   54 | 2012-01-03 00:00:00 |
|  4 | PHIL    |   51 |   70 | 2012-01-01 00:00:00 |
|  5 | PHIL    |   50 |   85 | 2012-01-01 00:00:00 |
|  6 | BOSTON  |   35 |   45 | 2012-01-01 00:00:00 |
|  7 | NOLA    |   65 |   85 | 2012-01-01 00:00:00 |
|  8 | HOUSTON |   60 |   70 | 2012-01-01 00:00:00 |
|  9 | CHICAGO |   50 |   90 | 2012-01-01 00:00:00 |
| 10 | LA      |   60 |   70 | 2012-01-01 00:00:00 |
| 11 | LA      |   55 |   72 | 2012-01-02 00:00:00 |
| 12 | LA      |   60 |   70 | 2012-01-03 00:00:00 |
| 13 | LA      |   60 |   70 | 2012-01-04 00:00:00 |
+----+---------+------+------+---------------------+

Example: Take first row NYC (id=1) , it should return:

id=2  (because 59 < 65 high)
id=4 (because 59 < 70 high )
id=5 (because 50 >= 50 (low) and 59 <= 85) 
...

Sounds like a job for a sub query but Im not sure...

Was it helpful?

Solution

If I understand this right, you don't need a subquery, just a self-join:

SELECT main.id, main.name, related.id, related.name
FROM yourtable AS main
INNER JOIN yourtable AS related ON
    (main.id <> related.id) AND (main.low >= related.low) AND (main.high <= related.high)

The main.id <> related.id bit will keep a city from matching itself.

OTHER TIPS

If I understand correctly, joining the table on itself will get you what you want:

SELECT matching.name
  FROM temps AS current
  JOIN temps AS matching on (matching.low <= current.low AND matching.high >= current.high AND matching.id != current.id)

This will get all rows that have temperatures ranges that encompass the current row's (except for itself).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top