JSON_TABLE关联查询致订单数据重复问题求助
解决JSON_TABLE关联导致订单数据重复的问题
数据重复的原因
当:todayStart参数为空时,你的SQL会把orders表和JSON_TABLE解析出的所有items记录做笛卡尔积关联。如果某条订单的items数组里有N个元素,这条订单就会被返回N次,因此出现重复数据。
解决办法
你需要实现仅当参数非空时才通过JSON_TABLE筛选items,参数为空时直接返回原订单数据的逻辑,以下是两种可行方案:
方案1:条件LEFT JOIN+去重
通过LEFT JOIN结合关联条件,让参数为空时不产生笛卡尔积,参数非空时才关联筛选符合条件的items:
select distinct o.* from orders o left join json_table( o.items, '$[*]' columns( startDate datetime path '$.startDate' ) ) as items on :todayStart is not null and datediff(items.startDate, now()) = 0 where (:todayStart is null or items.startDate is not null)
这里用distinct确保参数非空时,不会因为订单有多个符合条件的items而返回重复订单;参数为空时,LEFT JOIN不会产生额外行,直接返回原订单数据。
方案2:UNION ALL拆分逻辑
把“参数为空”和“参数非空”的情况拆成两个独立查询,用UNION ALL合并,逻辑更直观,性能也更优:
-- 参数为空时返回所有订单 select * from orders where :todayStart is null union all -- 参数非空时筛选符合条件的订单 select distinct o.* from orders o join json_table( o.items, '$[*]' columns( startDate datetime path '$.startDate' ) ) as items on datediff(items.startDate, now()) = 0 where :todayStart is not null
这种方式完全避免了不必要的关联操作,同时distinct保证单个订单不会因多个符合条件的items被重复返回。
内容的提问来源于stack exchange,提问作者kozakl
相关产品推荐
相关产品推荐

