[MDEV-30744] WITH AS clause doesn't work with an outside column Created: 2023-02-27  Updated: 2023-02-28  Resolved: 2023-02-28

Status: Closed
Project: MariaDB Server
Component/s: compat80
Affects Version/s: 10.11.2
Fix Version/s: N/A

Type: Bug Priority: Major
Reporter: Jakub Szymanowski Assignee: Unassigned
Resolution: Not a Bug Votes: 0
Labels: MySQL8

Issue Links:
Duplicate
duplicates MDEV-19337 CTEs not working with outer references Closed
Relates
relates to MDEV-19078 Support lateral derived tables Open

 Description   

The following statement works in MySQL 8 but does not work in MariaDB 11 or 10.5:

CREATE DATABASE IF NOT EXISTS test;
USE test;
CREATE TABLE foo (id int, bar_id int);
CREATE TABLE bar (id int, bar_column varchar(255));
 
SELECT
    foo.id,
    foo.bar_id,
    (
        WITH cte AS (
            SELECT bar.bar_column
            FROM bar
            WHERE bar.id = foo.bar_id
        )
        SELECT
            cte.bar_column
        FROM cte
    )
FROM foo;

Is this intentional?
Granted, the above SELECT doesn't make much sense but this is a minimal code needed for reproducing this error. I assure you it makes sense in my actual case

Steps to reproduce:

1. Create a docker-compose.yml file with the following contents:

version: '3.5'
 
services:
    mysql:
        image: mysql:8
        container_name: mysql
        environment:
            MYSQL_DATABASE: test
            MYSQL_ROOT_PASSWORD: test
            MYSQL_PASSWORD: test
    mariadb:
        image: mariadb:10.11
        container_name: mariadb
        environment:
            MARIADB_ROOT_PASSWORD: test

2. Run `docker-compose up -d` to pull the images and run the containers
3. Run `docker exec -it mysql mysql -u root -ptest` to enter the MySQL database
4. Execute the above SQL statements - should result in "Empty set (0.01 sec)".
5. Exit the MySQL database
6. Run `docker exec -it mariadb mariadb -u root -ptest` to enter the MariaDB database
7. Execute SQL statements again and it will result in "ERROR 1054 (42S22): Unknown column 'foo.bar_id' in 'where clause'"

Optionally:
8. Change MySQL version in the docker-compose.yml file to 11.0-rc
9. Run `docker-compose down` to destroy everything
10. Run `docker-compose up -d` again and repeat steps 6 and 7 - same result.



 Comments   
Comment by Alice Sherepa [ 2023-02-28 ]

Thank you for the report. The problem is not cte, but lateral derived tables in general are not supported in MariaDB yet:

MariaDB [test]> SELECT 1,( SELECT dt.bar_column FROM (SELECT 1 FROM bar  WHERE foo.bar_id=1)dt ) FROM foo;
ERROR 1054 (42S22): Unknown column 'foo.bar_id' in 'where clause'

task - MDEV-19078

Generated at Thu Feb 08 10:18:34 UTC 2024 using Jira 8.20.16#820016-sha1:9d11dbea5f4be3d4cc21f03a88dd11d8c8687422.