以下代码,a left join b 能查询到数据,c 结果集单独查询无数据。
现在出现了一个诡异的问题:整个 SQL 查询 c.submit_id 既然有数据,应该为 NULL 才对。
如果将 SELECT t1.*, t2.input_name,t2.sort_number 加一个 DISTINCT 就正常了。
SELECT
a.user_id AS userId,
b.org_name AS deptName,
c.submit_id AS submitId,
FROM
USER a
LEFT JOIN org b ON a.org_id = b.org_id
LEFT JOIN (
SELECT t1.*, t2.input_name,t2.sort_number
FROM questionnaire_result t1
JOIN template_form t2 ON t1.input_id = t2.input_id
WHERE EXISTS (select 1 from questionnaire_result x where t1.submit_id = x.submit_id and x.questionnaire_id = 'q1' and x.is_deleted= 0 and x.input_id = 't1f1' and x.content_name = '2022-03-241')
) c ON a.user_id = c.creator_id
WHERE a.is_deleted = 0
前后执行 explain 对比:
PS:在 10.5.5-MariaDB 没有问题。