Bug #103052 regression in CTE with multiple references
Submitted: 21 Mar 2021 9:45 Modified: 26 Mar 2021 8:58
Reporter: Jochem van Dieten Email Updates:
Status: Duplicate Impact on me:
None 
Category:MySQL Server: Optimizer Severity:S2 (Serious)
Version:8.0.18, 8.0.23 OS:Other (official Docker image)
Assigned to: CPU Architecture:Any
Tags: cte, regression

[21 Mar 2021 9:45] Jochem van Dieten
Description:
A query with a CTE that is used twice is not returning any records in MySQL 8.0.18 and later, while it did produce records in 8.0.17.

How to repeat:
CREATE TABLE `partner` (
  `id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `instructions` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `partner` 
VALUES ('414a0656-02e3-4409-b935-1385927e6e87','x');

CREATE TABLE `timeslot` (
  `id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `fromTime` time DEFAULT NULL,
  `toTime` time DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `timeslot` 
VALUES
  ('0376d1cf-9f48-4bdf-94d2-6e30b82e525d','15:00:00','23:59:59'),
  ('33460608-3e53-48d7-8614-dcd3a556ce73','09:00:00','14:59:59'),
  ('8c882eb2-4
87f-499b-bc95-9a260bf288d5','00:00:00','08:59:59');

WITH dates AS (
  SELECT '2021-03-28' as theDate, DAYOFWEEK( '2021-03-28' ) as dow
)
, partnerDays as (
  SELECT *, 1 as dow FROM partner
  UNION
  SELECT *, 2 as dow FROM partner
)
, allSlots AS (
  SELECT DISTINCT s.*
  FROM (
    SELECT *, 1 as dow FROM timeslot
    UNION ALL
    SELECT *, 2 as dow FROM timeslot
    ) s
    INNER JOIN partnerDays pd ON pd.dow = s.dow
)
, expandedSlots as (
  SELECT
    timestamp(d.theDate, s.fromTime) AS slotstart
    , timestamp(d.theDate, s.toTime) AS slotend
  FROM allSlots s
    INNER JOIN dates d ON s.dow = d.dow
)
, largestInterval as (
  SELECT 
    min(slotstart) as firstSlotStart, max(slotend) as lastSlotEnd
  FROM expandedSlots
)
-- select * from expandedSlots
-- select * from largestInterval
select * from expandedSlots, largestInterval;

Observations:
- worked in 8.0.17 (official Docker image)
- doesn't work in 8.0.18-23 (official Docker images)
- both expandedSlots and largestInterval individually produce rows (commented out), but together in a cartesian join they don't
- dropping the instructions text column in the partner table makes the query work.

Suggested fix:
Possibly a duplicate of https://bugs.mysql.com/bug.php?id=102251
[21 Mar 2021 10:29] MySQL Verification Team
Hello Jochem,

Thank you for the report and test case.
Verified as described.

regards,
Umesh
[26 Mar 2021 8:58] Erlend Dahl
Duplicate of

Bug#102251 CTE produces wrong result
[12 Dec 2022 22:52] Jon Stephens
BUG#102251 is fixed in MySQL 8.0.33.