我必须遵循以下表格:
CREATE TABLE IF NOT EXISTS `ebets_odds` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`datetime` datetime NOT NULL,
`match_id` int(11) NOT NULL,
`opponent_id` int(11) NOT NULL,
`value` float NOT NULL,
PRIMARY KEY (`id`),
KEY `match_id` (`match_id`),
KEY `opponent_id` (`opponent_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `ebets_odds` (`id`, `datetime`, `match_id`, `opponent_id`, `value`) VALUES
(1, '2013-09-04 23:09:39', 1, 1, 1.2),
(2, '2013-09-04 23:09:39', 1, 2, 1.8),
(3, '2013-09-05 11:54:10', 1, 1, 1.1),
(4, '2013-09-05 11:54:10', 1, 2, 1.9);
我想获得以下SQL结果:
2013-09-04 23:09:39 | 1.2 | 1.8
2013-09-05 11:54:10 | 1.1 | 1.9
所以我想按日期时间分组。 我尝试过这个,但它不起作用。
SELECT ODDS_1.datetime, ODDS_1.value AS odds_1, ODDS_2.value AS odds_2
FROM ebets_odds ODDS_1, ebets_odds ODDS_2
WHERE ODDS_1.match_id = 1 AND ODDS_2.match_id = 1
GROUP BY ODDS_1.datetime
答案 0 :(得分:1)
这是一个透视查询。您似乎想要了解不同列中两个对手的信息。您可以使用条件聚合执行此操作:
SELECT o.datetime,
max(case when opponent_id = 1 then o.value end) AS odds_1,
max(case when opponent_id = 2 then o.value end) AS odds_2
FROM ebets_odds o
WHERE match_id = 1
GROUP BY o.datetime;
答案 1 :(得分:0)
对于某些用例,可以使用group_concat
函数解决此问题:它将列中的值作为逗号分隔列表返回。如果逗号不适合您,您可以选择其他分隔符。然后必须在应用程序中处理该列表。
SELECT ODDS_1.datetime, GROUP_CONCAT(ODDS_1.value)
FROM ebets_odds ODDS_1
WHERE ODDS_1.match_id = 1
GROUP BY ODDS_1.datetime
输出:
2013-09-04 23:09:39 | 1.2,1.8
2013-09-05 11:54:10 | 1.1,1.9