0

假设我有以下表结构

CREATE TABLE `calendar` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `date` DATE NOT NULL,
  PRIMARY KEY (`id`)
)

以及以下数据

INSERT INTO `calendar` (`title`, `date`)
VALUES ('Day 1 - Event 1', '2013-05-01'),
('Day 2 - Event 1', '2013-05-02'),
('Day 2 - Event 2', '2013-05-02'),
('Day 3 - Event 1', '2013-05-03');

我希望将结果集限制为 2 个项目,但不要在同一日期的项目之间削减结果。

SELECT *
FROM `calendar`
WHERE `date` >= '2013-05-01'
LIMIT 2

屈服

('Day 1 - Event 1', '2013-05-01'),
('Day 2 - Event 1', '2013-05-02'),
('Day 2 - Event 2', '2013-05-02')

而不仅仅是

('Day 1 - Event 1', '2013-05-01'),
('Day 2 - Event 1', '2013-05-02')

有任何想法吗?

4

3 回答 3

3

像这样的东西应该可以将您想要的日期放在子查询中:

SELECT DISTINCT c.* 
FROM `calendar` c
  JOIN (
       SELECT `date`
       FROM `calendar`
       WHERE `date` >= '2013-05-01'
       LIMIT 2
    ) c2 on c.`date` = c2.`date`

SQL 小提琴演示

我建议ORDER BY在您的查询中添加一个日期,因为如果没有,您无法保证结果的顺序。

于 2013-05-02T19:07:35.863 回答
1

如果我理解正确,您想显示前 2 项,但如果最后一项(在日期上)有平局,也包括平局结果。SQL-Server 有TOP (2) WITH TIES,但不幸的是 MySQLLIMIT没有对应的。因此,查询必须更复杂:

SELECT *
FROM calendar
WHERE `date` >= '2013-05-01'
  AND `date` <= COALESCE(
       ( SELECT `date`
         FROM calendar
         WHERE `date` >= '2013-05-01'
         ORDER BY `date`
           LIMIT 1 
           OFFSET 1                          -- that's 2 minus 1
       ), '9999-12-31'  )
  ;

另一种方式,类似于@sgeddes 的回答:

SELECT c.* 
FROM calendar c
  JOIN 
    ( SELECT DISTINCT `date`
      FROM
        ( SELECT `date`
          FROM `calendar`
          WHERE `date` >= '2013-05-01'
          ORDER BY `date`
            LIMIT 2
        ) AS c2
    ) AS cc 
      ON c.`date` = cc.`date` ;
于 2013-05-02T19:09:11.423 回答
-1

您可以使用 DISTINCT 子句。

SELECT DISTINCT(DATE),attrib2,attrib3,......
FROM `calendar`
WHERE `date` >= '2013-05-01'
LIMIT 2
于 2013-05-02T18:57:04.610 回答