I have some information that's stored like this:
DROP TABLE IF EXISTS `demographics`;
CREATE TABLE IF NOT EXISTS `demographics` (
`row_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`city_id` int(10) unsigned NOT NULL,
`until_year` int(10) unsigned DEFAULT NULL,
`population` int(10) unsigned NOT NULL,
PRIMARY KEY (`row_id`)
) ENGINE=InnoDB;
INSERT INTO `demographics` (`row_id`, `city_id`, `until_year`, `population`) VALUES
(1, 1, NULL, 1300),
(2, 1, 2009, 1250),
(3, 1, 2008, 1000),
(4, 1, 2004, 800);
So:
SELECT until_year, population
FROM demographics
WHERE city_id=1
ORDER BY until_year IS NOT NULL, until_year DESC;
... displays:
+------------+------------+
| until_year | population |
+------------+------------+
| NULL | 1300 |
| 2009 | 1250 |
| 2008 | 1000 |
| 2004 | 800 |
+------------+------------+
The information needs to be displayed like this:
+------+------------+
| Pop. 2000-Present |
+------+------------+
| year | population |
+------+------------+
| 2010 | 1300 |
| 2009 | 1250 |
| 2008 | 1000 |
| 2007 | 1000 |
| 2006 | 1000 |
| 2005 | 1000 |
| 2004 | 800 |
| 2003 | 800 |
| 2002 | 800 |
| 2001 | 800 |
| 2000 | 800 |
+------+------------+
My first step was to hard-code the years (other techniques looked like overcomplicating it):
DROP TABLE IF EXISTS `year`;
CREATE TABLE IF NOT EXISTS `year` (
`year` int(10) unsigned NOT NULL,
PRIMARY KEY (`year`)
) ENGINE=InnoDB;
INSERT INTO `year` (`year`) VALUES
(2000),
(2001),
(2002),
(2003),
(2004),
(2005),
(2006),
(2007),
(2008),
(2009),
(2010),
(2011),
(2012),
(2013),
(2014),
(2015);
Assuming that 2000 is a parameter and 2010 is YEAR(NOW())
, I think I have all the information required to start joining tables. But I'm lost with the details. How can I relate each row with the years they represent?