0

我必须下表:

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
4

2 回答 2

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;
于 2013-09-05T13:19:03.227 回答
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
于 2013-09-05T13:16:17.447 回答