场景
- 写sql时,会出现大量的left join的情况,针对这种方式提供 两种解决方案。
解决方案
方案一
- 宽表,但是其维护性差
方案二
- JSON类型字段
将业务查询的一些实体类 直接以JSON的形式存到数据库,以下是SQL代码查询的实例
data(“customer” :{“id”:“111”,“name”:“123”},“product” :{“id”:“111”,“name”:“123”});
select json_unquote(data -> '$.order_id') as order_id, json_unquote(data -> '$.customer.name') as customer_name from this_tablewhere data-> '$.customer.id' = 11;
- 以上SQL便是查询的案例,但是其存在问题就是 不走索引 。
解决方案为,建立一个虚拟列以 customer.id 为例
alter table this_table add customer_id int as (json_unquote(data -> '$.customer.id')) virtual;create index idx_customer_id on this_table(customer_id);
- 通过执行计划可以查看 是走索引的,至此优化完成。(可以结合项目需要进行优化)