0
CREATE TABLE table
 (`id` int, `date` date, `time` time);
INSERT INTO table
  (`id`, `date`, `time`)
 VALUES  
 (1, '2022-05-22', 14:00:00),
 (2, '2022-05-23', 07:35:00),
 (4, '2022-05-23', 14:00:00);

Expected Output:

date time
2022-05-22 14:00:00
2022-05-22 NULL
2022-05-23 07:35:00
2022-05-23 14:00:00

As you notice, there's no entry for 07:35 at date 2022-05-22.

I have tried join on single table and CTE also but nothing works.

I'm using PHP with MySQL

Thanks in advance.

lemon
  • 14,875
  • 6
  • 18
  • 38
Shravan Sharma
  • 989
  • 8
  • 17

2 Answers2

2

A calendar table approach might be what you are looking for. Consider the following select query which however generates the exact output you want.

WITH dates AS (
    SELECT '2022-05-22' AS dt UNION ALL
    SELECT '2022-05-23'
),
times AS (
    SELECT '07:35:00' AS tm UNION ALL
    SELECT '14:00:00'
)

SELECT d.dt AS date, yt.time
FROM dates d
CROSS JOIN times t
LEFT JOIN yourTable yt
    ON yt.date = d.dt AND
       yt.time = t.tm
ORDER BY d.dt, t.tm;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Solution given by @Tim Biegeleisen is working just fine but unfortunately my server doesn't suppoert CTE, so who has little knowledge of CTE or have lower version of mysql can try this solution...

SELECT DISTINCT(d.dt) AS date, yt.time
FROM (SELECT date as dt FROM tableName ) as d 
CROSS JOIN (SELECT time as tm FROM tableName ) as t
LEFT JOIN tableName yt
ON yt.date = d.dt AND yt.time = t.tm
ORDER BY d.dt, t.tm;
Shravan Sharma
  • 989
  • 8
  • 17