mysql 需要连接一个表多次,很慢。如何解决?

表A 有22个字段与表B的id关联,然后我希望得到表B的unitprice字段,现在我使用的是

select A.id,A.name,A.a01,b1.unitprice as a01_unitprice,...,A.a22,b22.unitprice as a22_unitprice    from A                        
left join B as b1 on A.a01 = b1.id
left join B as b2 on A.a02 = b2.id
...
left join B as b22 on A.a22 = b22.id
where A.id = ${id}

表A有15000条数据
表B有3000条
现在的查询耗时10s+
有什么更快的方法吗?

A表

idnamea01a02a03...a22
1hello1255241...51

B表

idnameunitprice
1aa34
27wdr69
.........
阅读 2.9k
3 个回答

你知道你这么查相当于有多少行么?

15000^20次

select * from A, B where A.id = {id} and (A.a01 = B.id or A.a02 = B.id ...)

建议调整表结构,在A表中记录不同字段的单价,例如:a01_unitprice,a22_unitprice...
在A表数据被修改时从B表获取单价,如果需要获取B表最新的单价,那就在B表单价改变的同时修改A表中相关的单价。

数据先读出来,代码层面拼接数据

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题