Skip to content

MySQL Compatibility: JOIN column reference remapping error in nested correlated subqueries #23083

Closed

Description

@dengn

Description

MatrixOne encounters a query optimizer error when processing nested correlated subqueries in SELECT clauses. The error occurs when a correlated subquery contains an IN subquery, causing the query optimizer to fail in mapping column references during JOIN operations.

Error Message

ERROR 1064 (HY000) at line 1: SQL parser error: remapInfo step 0 nodeId 11 nodeType JOIN tip OnList colRefCnt:[[12 0] : 0][[18 1] : 0][[18 3] : 0][[3 0] : 1][[3 1] : 1][[3 2] : 1][[1 0] : 1][[2 0] : 1][[6 21] : 0][[7 0] : 0][[20 0] : 0][[8 0] : 2][[20 1] : 0][[12 21] : 0]colRefBool:[[0 1] : true][[0 2] : true][[0 0] : true]sinkColRef:ColRefRemapping{globalToLocallocalToGlobal}empty ColRefRemapping srcExprIdx 0  ; can't find column [6 21] in context's map { [1 0], [2 0], [7 0], [8 0] }

Affected Cases

This issue affects 2 test cases from our nested subquery compatibility testing on the industry_radar_test database.

Related Table DDL

Table: company

CREATE TABLE `company` (
  `id` int NOT NULL,
  `full_name` varchar(200) DEFAULT NULL,
  `short_name` varchar(128) DEFAULT NULL,
  `update_time` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '最后修改时间',
  `address` varchar(255) DEFAULT NULL,
  `board_id` int DEFAULT NULL,
  `business_scope` text DEFAULT NULL,
  `city` varchar(32) DEFAULT NULL,
  `company_profile` text DEFAULT NULL,
  `company_type_tags` varchar(255) DEFAULT NULL,
  `country` varchar(20) DEFAULT NULL,
  `directory_label` varchar(512) DEFAULT NULL,
  `district` varchar(32) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `english_name` varchar(255) DEFAULT NULL,
  `enterprises_type` varchar(50) DEFAULT NULL,
  `founded_time` datetime(6) DEFAULT NULL,
  `industry` varchar(32) DEFAULT NULL,
  `industry_paqu` varchar(1000) DEFAULT NULL,
  `insured_num` varchar(32) DEFAULT NULL,
  `product_label` varchar(512) DEFAULT NULL,
  `province` varchar(32) DEFAULT NULL,
  `registered_capital` varchar(50) DEFAULT NULL,
  `representative` varchar(32) DEFAULT NULL,
  `taxpayer_num` varchar(50) DEFAULT NULL,
  `telephone` varchar(255) DEFAULT NULL,
  `website` varchar(500) DEFAULT NULL,
  `industry_web_label` varchar(512) DEFAULT NULL COMMENT '国标行业标签',
  `industry_domain_label` varchar(512) DEFAULT NULL COMMENT '素问产业链标签',
  `scale` varchar(255) DEFAULT NULL COMMENT '规模标签',
  `policy_type` varchar(512) DEFAULT NULL COMMENT '政策类型标签',
  PRIMARY KEY (`id`),
  UNIQUE KEY `company_full_name_idx` (`full_name`),
  UNIQUE KEY `company_short_name_idx` (`short_name`),
  KEY `company_board_id_idx` (`board_id`),
  KEY `company_city_idx` (`city`),
  KEY `company_province_idx` (`province`)
)

Table: company_patent

CREATE TABLE `company_patent` (
  `id` int NOT NULL,
  `company_id` int DEFAULT NULL,
  `name` varchar(512) DEFAULT NULL,
  `status` varchar(50) DEFAULT NULL,
  `patent_type` varchar(50) DEFAULT NULL,
  `num` varchar(100) DEFAULT NULL,
  `public_date` date DEFAULT NULL,
  `application_date` date DEFAULT NULL,
  `update_time` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '最后修改时间',
  PRIMARY KEY (`id`),
  KEY `company_id_idx` (`company_id`),
  KEY `status_idx` (`status`)
)

Table: news_company

CREATE TABLE `news_company` (
  `id` int NOT NULL,
  `company_id` int DEFAULT NULL,
  `news_id` int DEFAULT NULL,
  `release_time` datetime DEFAULT NULL,
  `extract_type` varchar(50) DEFAULT NULL,
  `is_hot` smallint DEFAULT NULL,
  `polarity` smallint DEFAULT NULL,
  `update_time` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '最后修改时间',
  PRIMARY KEY (`id`),
  KEY `company_id_idx` (`company_id`),
  KEY `news_id_idx` (`news_id`)
)

Failing SQL Statements

Example 1: Correlated subquery with IN subquery in SELECT

SELECT c.province,
       (SELECT COUNT(DISTINCT c2.id)
        FROM company c2
        WHERE c2.province = c.province
        AND c2.id IN (
            SELECT company_id FROM company_patent WHERE status = '授权'
        )
       ) as companies_with_patents,
       COUNT(*) as total_companies
FROM company c
WHERE c.province IS NOT NULL
GROUP BY c.province
LIMIT 10;

Error: ERROR 1064 (HY000): SQL parser error: remapInfo step 0 nodeId 11 nodeType JOIN tip OnList ... can't find column [6 21] in context's map

Example 2: JOIN with derived table containing correlated subquery

SELECT c.full_name,
       subq.patent_count,
       subq.news_count
FROM company c
INNER JOIN (
    SELECT cp.company_id,
           COUNT(cp.id) as patent_count,
           (SELECT COUNT(*)
            FROM news_company nc
            WHERE nc.company_id = cp.company_id
           ) as news_count
    FROM company_patent cp
    WHERE cp.company_id IN (
        SELECT id FROM company WHERE province = '广东'
    )
    GROUP BY cp.company_id
) as subq ON c.id = subq.company_id
LIMIT 10;

Error: ERROR 1064 (HY000): SQL parser error: remapInfo step 0 nodeId 12 nodeType JOIN tip OnList ... can't find column [12 1] in context's map

Expected Behavior

In MySQL, nested correlated subqueries with IN subqueries in SELECT clauses execute successfully. The query optimizer should correctly map column references across all levels of nesting.

Impact

  • MySQL Compatibility: This is a standard MySQL feature that should work correctly
  • Migration: Applications using nested correlated subqueries will fail when migrating to MatrixOne
  • Functionality: Users cannot use correlated subqueries with nested IN subqueries in SELECT clauses
  • Query Complexity: Limits the complexity of analytical queries that can be executed

Root Cause Analysis

The error occurs in the query optimizer's column reference remapping logic:

  1. When processing JOIN operations in nested subqueries
  2. The optimizer fails to correctly map column references ([6 21], [12 1]) to the context map
  3. This suggests an issue in the remapInfo logic during query plan generation
  4. The problem appears to be in how column references are tracked across nested query levels

Test Context

This issue was discovered during nested subquery compatibility testing using the industry_radar_test database, which contains:

  • company table with ~766K records
  • company_patent table with ~1.2M records
  • news_company table with ~1.5M records

Suggested Fix

  1. Query Optimizer: Review and fix the column reference remapping logic in the query optimizer
  2. Column Reference Tracking: Ensure column references are correctly tracked across nested query levels
  3. JOIN Processing: Fix the JOIN column reference mapping when processing nested correlated subqueries
  4. Error Handling: Improve error messages to provide more context about which column reference failed
  5. Testing: Add comprehensive tests for nested correlated subqueries with IN subqueries
  6. Code Review: Review remapInfo logic in the query optimizer, particularly for JOIN operations with nested subqueries

Activity

  1. Ariznawlll commented on Jul 22, 2026

    @Ariznawlll
    Collaborator

    补充测试场景与结果

    发现一个更小、且不需要嵌套 IN 的触发场景:在同一层 SELECT 中并列放置一个相关 EXISTS 和一个相关标量聚合子查询时,两个子查询单独执行都正常,组合后会在列映射阶段失败。

    CREATE TABLE t(id INT PRIMARY KEY, parent_id INT, v INT);
    INSERT INTO t VALUES (1,NULL,10),(2,1,20),(3,1,30);
    
    SELECT b.id,
           EXISTS(SELECT 1 FROM t x WHERE x.id=b.parent_id) AS parent_exists,
           (SELECT MAX(v) FROM t x WHERE x.id<=b.id) AS prefix_max
    FROM t b
    ORDER BY b.id;

    测试结果:

    • 仅保留 EXISTS:正常返回 3 行。
    • 仅保留标量聚合子查询:正常返回 10 / 20 / 30。
    • 两者并列:连续 3 次均返回 Column remapping failed: cannot find column reference,失败节点为 PROJECT,提示为 neededProj。
    • 将基表子查询替换为同一个 CTE 的两个消费者后,结果相同。
    • MySQL 8.0.45 返回:(1,0,10) / (2,1,20) / (3,1,30)。

    这个场景表明列映射缺口还覆盖“同层多个不同形态的相关子查询”,不仅限于原 issue 中“相关子查询内部再包含 IN”的结构。

  2. Ariznawlll commented on Oct 14, 2026

    @Ariznawlll
    Collaborator

    当前 main 复核(2026-10-14)

    在 MatrixOne 2ce4e58af6f03b943ee288ffad81012766cf830a 与 MySQL 8.0.46 上,按本 issue 已有的最小复现重新测试:相关 EXISTS 与相关标量聚合分别执行、两者同层并列(两种投影顺序)、同类子查询重复消费者、CTE/派生表消费者,均连续 3 次返回相同且与 MySQL 一致的结果。issue 中两个嵌套 IN / derived-correlation 查询形态也用简化表结构重放并与 MySQL 一致。

    因此,这些最小结构在当前 main 上未重现原列重映射错误。此次没有使用完整 industry_radar_test 数据库、全部索引和原始大表,故这不是对原业务 schema 的完整复验,也不据此判断 issue 已整体解决;如原 schema 上仍可复现,建议保留完整 DDL、索引和 EXPLAIN 继续比对。

  3. added a commit that references this issue on Oct 22, 2026
    d7f95aa
  4. XuPeng-SH commented on Oct 22, 2026

    @XuPeng-SH
    Contributor

    Verified on main@3ad9adbb4c — original repro no longer fails

    Local CGo build, isolated instance, the issue's own SQL blocks run verbatim (5 blocks: the company / related DDL plus both failing queries):

    === block 0..2 ===  DDL applied (tables created)
    === block 3 ===     nested correlated subquery with IN  -> Empty set, no planner error
    === block 4 ===     company_patent join aggregate       -> Empty set, no planner error
    

    No remapInfo ... can't find column [6 21] in context's map error appeared; the queries plan and execute.

    Scope note: the tables are empty, so this proves the planner column-remapping failure is gone on this path — it does not prove row-level result correctness on populated data. If you want that covered, the same queries need to be re-run on the populated industry_radar_test dataset.

    Keeping Ariznawlll as the single assignee for regression verification.

  5. Ariznawlll commented on Oct 23, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:官方 matrixorigin/matrixone main
    • commit:bc84bd142600b745503e225cb89cb1526df8d35e(执行前及报告前复查,隔离构建 go version -m 显示同一完整 SHA、vcs.modified=false)
    • 修复:#30834 已 MERGED,merge commit d7f95aa754bfe39126752729d307298710947c17;GitHub compare 为 ahead 29 / behind 0,确认包含于上述 main。该 PR 的新增修复范围是 inline CTE 私有行身份传递;原两条嵌套 IN 查询在修复前基线上已经能规划,不能将其既有成功归功于该 PR。
    • 部署方式:macOS arm64 隔离本地服务,1 LOG / 1 TN / 1 CN,真实 MySQL TCP;未使用共享 TKE、128/129 或外部故障注入。
    • 测试日期:2026-10-23(北京时间)

    原问题验证

    每轮创建全新数据库,使用 issue 中 company、company_patent、news_company 的完整列和索引布局(仅省略不影响计划的列注释),分别插入 5、6、4 条非空/NULL/重复关联的可核算数据,再原样执行 issue 的两条 SQL。连续 3/3 轮均无 remapInfo / Column remapping failed:第一条按省份得到 广东:(1,2)、广西:(0,1)、浙江:(1,1)(括号内依次为授权专利公司数、公司总数);第二条得到 a:(2,2)、b:(1,1)(专利数、新闻数)。不是只在空表上验证能规划。

    Happy Path 覆盖

    1. 原始两条查询各 3 次,逐行核对上述值,均通过。
    2. 与 PR 实际修复范围对应的 WITH q AS (SELECT * FROM tree_rows):同一 SELECT 中并列相关 EXISTS 与相关 MAX,3/3 返回 (1,0,10) / (2,1,20) / (3,1,30)。
    3. 无主键且包含 NULL/重复行的 inline CTE,同时取 EXISTS、MAX、COUNT(*)、COUNT(v):3/3 返回 (NULL,7,0,NULL,0,0)、(0,NULL,1,NULL,1,0)、两个 (2,10,1,10,3,2);重复行没有丢失或合并。
    4. 空内层 CTE:3/3 对四条外层行均返回 MAX=NULL、COUNT(*)=0。每轮测试后删除隔离数据库并确认不存在。

    Unhappy Path 覆盖

    1. UNION ALL 会复制候选行身份的受保护 CTE 形态,3/3 按该 PR 明确保留的边界返回错误码 20102,未把不支持形态写成成功结果。
    2. 每次上述拒绝后,bag_rows 仍为 COUNT(*)=4, SUM(v)=27,原正常 CTE 查询再次返回三条预期值;没有污染后续连接和数据。

    白盒验证

    本轮为独立 MySQL 协议黑盒验收,没有重新运行包内 Go 测试。合并 PR 已包含 pkg/tests/sqlintegration/correlated_cte_identity_test.go 与 test/distributed/cases/subquery/scalar_cte_row_identity.sql,涵盖原完整索引 DDL、CTE/NULL/重复行、空输入、预编译复用和受保护拒绝;本轮黑盒逐项复核了上述公共 SQL 核心路径。未测原 industry_radar_test 的约 76.6 万 / 120 万 / 150 万业务行,也未把本地单 CN 当作性能或分布式验证;本 issue 验收的是列引用映射与结果正确性,不是吞吐阈值。

    回归测试

    已有合并的确定性 SQL BVT 与 真实前端 SQL 集成测试,所以没有再复制相同断言到 MOTR,也没有向 MO 新提 PR。本轮未跑完整本地 BVT suite;PR 的 CI Required、Ubuntu/x86 UT、多 CN BVT 显示 PASS;部分其他矩阵标为 skipping,不称完整矩阵全绿。

    测试证据

    • 独立黑盒脚本保存在本地 /tmp/mo-30045-superset-HicFlq/qa_23083_sql.py(本地文件并非公开下载制品);三轮输出均为 original_queries=2, cte_cases=3, guarded_error=20102, rows_intact=[4,27],最终 status=PASS, runs=3, cleanup=true。
    • 上述 PR 的源码测试文件和 CI 链接可独立核查。未复跑 MySQL 对照或原业务全量数据;PR 描述记录的 MySQL 8.4.8 对照不冒充本轮执行。

    测试结论

    测试通过。

  6. XuPeng-SH commented on Oct 25, 2026

    @XuPeng-SH
    Contributor

    Fresh-round supplementary SQL validation on pinned MatrixOne main.

    • Source: aeaa273daf588a9988ba423915d3ae6b8c82124a; target merge: d7f95aa754bfe39126752729d307298710947c17.
    • Runtime binary SHA-256: 450363d5ec5e693bdd7ded44565b3b0ab1addcb807d3f9569c5d5eedeb1486e4. Isolated single-CN MySQL service, version 8.0.30-MatrixOne-v1.3.0.
    • 13/13 SQL assertions passed on populated deterministic fixtures. Both original query shapes returned expected values; additional cases covered duplicate and NULL CTE rows, correlated EXISTS/MAX/COUNT, renamed CTE columns, empty inner input, and prepared-query reuse across an empty result, guarded error, and later insert.
    • The intentional duplicate-identity UNION ALL shape remained rejected with expected error 20102. Isolated database cleanup was verified.

    Scope is single-CN SQL with reduced deterministic data. This run did not import the full industry_radar_test database or run Go/race/multi-CN coverage. Issue #23083 was already closed and assigned to Ariznawlll, so I left its assignment unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions