我有四张 table
store[store_id(pk),name]
itemsA(item_id(pk),store_id,name)
itemB(item_id(pk),store_id,name)
itemC(item_id(pk),store_id,name)
我想要一个查询来检索商店及其拥有的商品数量。类似的东西:
select s.store_id ,s.name,count() as numberOfItems from store limit 100
在以下限制下实现这一目标的最佳查询是什么: 无法在数据库中创建函数 无法创建 View 我只能在数据库上运行查询 谢谢
最佳答案
我建议使用相关子查询来执行此操作:
select s.store_id, s.name,
((select count(*) from itemsA a where a.store_id = s.store_id) +
(select count(*) from itemsB b where b.store_id = s.store_id) +
(select count(*) from itemsC c where c.store_id = s.store_id)
) as numberOfItems
from store s
limit 100;
然后,您需要在每个项目表中都有一个索引:itemsA(stored_id)
、itemsB(store_id)
和 itemsC(store_id)
.
之所以进行优化,是因为它只需计算 limit
选择的任意 100 个商店的值。并且,可以直接根据索引进行计算。其他方法需要对所有商店进行计算。
注意:通常在使用 limit
时,您需要一个 order by
子句。
关于mysql - 使用多个表的计算字段优化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26142465/