2

请帮忙查询。有一张桌子:

id | u_id | start_date |  end_date  |
-------------------------------------
01 |   7  | 2012-09-05 | 2012-09-23 |
02 |   4  | 2012-09-10 | 2012-09-15 |
03 |   4  | 2012-09-27 | 2012-10-05 |
04 |   5  | 2012-10-01 | 2012-10-09 |
05 |   4  | 2012-10-10 | 2012-10-15 |
06 |   7  | 2012-10-23 | 2012-11-05 |
07 |   5  | 2012-11-05 | 2012-11-12 |
08 |   4  | 2012-11-08 | 2012-11-10 |

我想从上个月选择月份= 10 和最大“start_date”以及从下个月开始的最小“end_date”的所有记录。结果需要

id | u_id | start_date |  end_date  |
-------------------------------------
03 |   4  | 2012-09-27 | 2012-10-05 |
04 |   5  | 2012-10-01 | 2012-10-09 |
05 |   4  | 2012-10-10 | 2012-10-15 |
06 |   7  | 2012-10-23 | 2012-11-05 |

我不明白我对这个查询做错了什么

SELECT start_date, end_date
FROM _xata_owner 
INNER JOIN (
   SELECT max(start_date) AS date FROM _xata_owner
   GROUP BY DATE_FORMAT(start_date, "%m")
   ) b ON month(b.date)=09
WHERE month(start_date)=10
ORDER BY start_date

谢谢!

4

1 回答 1

0

所以你要:

  • 获取 start_date 中月份为 10 的记录。为此:

    选择 id、u_id、start_date、end_date FROM _xata_owner WHERE month(start_date)=10

  • 获取上个月“start_date”所在的最大“end_date”:

    SELECT id、u_id、start_date、end_date FROM _xata_owner WHERE month(start_date) = 09 AND end_date = (SELECT MAX(end_date) FROM _xata_owner WHERE month(start_date) = 09)

  • 获取下个月“end_date”所在的最小“end_date”:

    SELECT id、u_id、start_date、end_date FROM _xata_owner WHERE month(end_date) = 11 AND end_date = (SELECT MIN(end_date) FROM _xata_owner WHERE month(end_date) = 11)

把它们放在一起:

(SELECT id, u_id, start_date, end_date
FROM _xata_owner 
WHERE month(start_date)=10)
UNION
(SELECT id, u_id, start_date, end_date
FROM _xata_owner
WHERE month(start_date) = 09 AND end_date =
        (SELECT MAX(end_date) FROM _xata_owner WHERE month(start_date) = 09))
UNION
(SELECT id, u_id, start_date, end_date
FROM _xata_owner
WHERE month(end_date) = 11 AND end_date =
        (SELECT MIN(end_date) FROM _xata_owner WHERE month(end_date) = 11))

无论如何,这听起来像你想要的。你的问题有点令人困惑。

于 2012-10-10T22:51:25.853 回答