需要帮助MySQL查询2个日期
表1
Date_Start | Date_End | No_ID
2014-10-10 | 2014-10-15 | 34
2014-10-20 | 2014-10-22 | 34
2014-10-14和2014-10-21之间的日期
我想要结果
No | No_ID | Date_result
1 | 34 | 2014-10-14
2 | 34 | 2014-10-15
3 | 34 | 2014-10-20
4 | 34 | 2014-10-21
表1中第1行没有1和2没有基础 没有3,没有4是表1第1行的基础
并且不使用" UNION"
答案 0 :(得分:0)
一种方法
SELECT @rn := @rn + 1 no, no_id, date_result
FROM
(
SELECT no_id, date_start + INTERVAL n.n - 1 DAY date_result
FROM
(
SELECT no_id,
GREATEST(t.date_start, s.date_start) date_start,
LEAST(t.date_end, s.date_end) date_end
FROM table1 t CROSS JOIN
(
SELECT '2014-10-14' date_start, '2014-10-21' date_end
) s
WHERE t.date_start BETWEEN s.date_start AND s.date_end
OR t.date_end BETWEEN s.date_start AND s.date_end
) q JOIN
(
SELECT 1 n UNION ALL
SELECT 2
-- add up to a max possible diff of days between date_start and date_end
-- or use a tally (numbers) table to avoid UNION here
) n
ON n.n - 1 <= DATEDIFF(q.date_end, q.date_start)
) q CROSS JOIN
(
SELECT @rn := 0
) i
ORDER BY no_id, date_result
输出:
| NO | NO_ID | DATE_RESULT | |----|-------|-------------| | 1 | 34 | 2014-10-14 | | 2 | 34 | 2014-10-15 | | 3 | 34 | 2014-10-20 | | 4 | 34 | 2014-10-21 |
这是 SQLFiddle 演示