let's imagine I have the following two tables
CREATE TABLE `articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`artId` int(11) NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `artId` (`artId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `priceHistory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`artId` int(11) NOT NULL,
`price` float NOT NULL,
`checkdate` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
And the following data
INSERT INTO `test`.`articles` (`id`, `artId`, `price`) VALUES (NULL, '1', '5'), (NULL, '2', '2'), (NULL, '3', '3'), (NULL, '4', '9.50'), (NULL, '5', '1.3');
INSERT INTO `test`.`priceHistory` (`id`, `artId`, `price`, `checkdate`) VALUES (NULL, '1', '5', '2014-11-10 04:19:56'), (NULL, '1', '8.50', '2014-11-09 04:19:56'), (NULL, '1', '2.5', '2014-11-08 04:19:56'), (NULL, '2', '2', '2014-11-10 04:19:56'), (NULL, '2', '2.5', '2014-11-09 04:19:56'), (NULL, '3', '3', '2014-11-10 04:19:56'), (NULL, '4', '9.50', '2014-11-10 04:19:56'), (NULL, '4', '10', '2014-11-09 04:19:56'), (NULL, '4', '8', '2014-11-08 04:19:56'), (NULL, '4', '7', '2014-11-07 04:19:56'), (NULL, '5', '1.3', '2014-11-10 04:19:56'), (NULL, '5', '2', '2014-11-09 04:19:56');
What I now want to do is the following. I want to select all articles from the table articles
and also have every price change / price history entry in the same row. As an example, the final result should look like this:
id articleId currentPrice 2014-11-07 2014-11-08 2014-11-09 2014-11-10
1 1 5 NULL 2.5 8.5 5
2 2 2 NULL NULL 2.5 2
3 3 3 NULL NULL NULL 3
4 4 9.5 7 8 10 9.5
5 5 1.3 NULL NULL 2 1.3
Basically, I want to select the dates from another table and put them in as column names and fill in the data accordingly. Is this somehow possible with SELECT? I found multiple ressources on this topic, but they were either for a fixed number of rows and I need it to have it dynamic, because the datetime could reach until next year (extreme example) or they were for just one table. These are the ressources I found
- Problems to select the correct row from a second table
- Using MySQL GROUP_CONCAT or PIVOT on multiple joined tables
- MySQL - How to display row value as column name using concat and group_concat
- Select dynamic Columns in mysql
- mysql select dynamic row values as column names, another column as value
- Mysql query to dynamically convert rows to columns
- MySQL - Rows to Columns
- http://buysql.com/mysql/12-how-to-pivot-tables.html