2016-01-02 44 views

回答

2

你可以使用計數表並添加多個30分鐘INTERVAL

SELECT DATE_FORMAT(timeA + INTERVAL n * 30 MINUTE, '%k:%i') as timeA, 
     DATE_FORMAT(timeA + INTERVAL (n+1) * 30 MINUTE , '%k:%i') as timeB, 
     CONCAT(DATE_FORMAT(timeA + INTERVAL n * 30 MINUTE, '%k:%i'),'-', 
     DATE_FORMAT(timeA + INTERVAL (n+1) * 30 MINUTE , '%k:%i')) as time_range 
FROM tab 
CROSS JOIN 
(
    SELECT a.N + b.N * 10 n 
    FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a 
    ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b 
) n 
WHERE timeA + INTERVAL (n+1) * 30 MINUTE <= timeB  

SqlFiddleDemo

輸出:

╔════════╦════════╦═════════════╗ 
║ timeA ║ timeB ║ time_range ║ 
╠════════╬════════╬═════════════╣ 
║ 12:00 ║ 12:30 ║ 12:00-12:30 ║ 
║ 12:30 ║ 13:00 ║ 12:30-13:00 ║ 
║ 13:00 ║ 13:30 ║ 13:00-13:30 ║ 
║ 13:30 ║ 14:00 ║ 13:30-14:00 ║ 
║ 14:00 ║ 14:30 ║ 14:00-14:30 ║ 
║ 14:30 ║ 15:00 ║ 14:30-15:00 ║ 
╚════════╩════════╩═════════════╝ 

隨着變量和支持的非神韻:間隙:

SET @gap = 45; 
SET @start = '11:00:00'; 
SET @end = '15:00:00'; 
SELECT CONCAT(DATE_FORMAT(timeA + INTERVAL n * @gap MINUTE, '%k:%i'),'-', 
     DATE_FORMAT(IF(timeA + INTERVAL (n+1) * @gap MINUTE < timeB, 
         timeA + INTERVAL (n+1) * @gap MINUTE, 
         timeB) , '%k:%i')) as time_range 
FROM 
    (SELECT CAST(@start AS TIME) AS timeA, CAST(@end AS TIME) AS timeB) AS tab 
CROSS JOIN 
(
    SELECT a.N + b.N * 10 n 
    FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a 
    ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b 
) n 
WHERE timeA + INTERVAL (n) * @gap MINUTE <= timeB 

SqlFiddleDemo2

輸出:

╔═════════════╗ 
║ time_range ║ 
╠═════════════╣ 
║ 11:00-11:45 ║ 
║ 11:45-12:30 ║ 
║ 12:30-13:15 ║ 
║ 13:15-14:00 ║ 
║ 14:00-14:45 ║ 
║ 14:45-15:00 ║  -- not 15.30 
╚═════════════╝ 
2

如果你可以使用順序引擎,你可以這樣做:

SELECT 
    CONCAT(
    "SELECT CONCAT (
    TIME('11:00') + interval ((seq-1) * 30) Minute, 
    ' - ', 
    TIME('11:00') + interval (seq * 30) Minute) AS time_range 
    FROM seq_1_to_", 
    CAST((TIME_TO_SEC(timediff('13:00','11:00')) /60/30) AS UNSIGNED) 
) INTO @sql; 
PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

輸出

+---------------------+ 
| time_range   | 
+---------------------+ 
| 11:00:00 - 11:30:00 | 
| 11:30:00 - 12:00:00 | 
| 12:00:00 - 12:30:00 | 
| 12:30:00 - 13:00:00 | 
+---------------------+ 
4 rows in set (0.00 sec) 
相關問題