mysql - 使用多个表的计算字段优化查询

标签 mysql sql

我有四张 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/

相关文章:

java - 在 GWT 应用程序中使用 jdbc 连接到 mysql (xampp) 时遇到问题 - 即使 jar 在构建路径中也找不到类

php - 如何使用 PHP 正确更新 SQL 表行

mysql - 插入语句难度

mysql - 如何手动将.h文件导入系统库?

MySQL 格式数字,小数位数未知

java - 使用列索引而不是列名称插入 SQL Derby

mysql - SQL 查询以查找其中包含多个字符串 "a href"的列

mysql - 具有重复值的 JOIN 上的更新表仅返回第一个值

MySQL 使用来自另一个表的信息更新一个表

php - 将 utf-8 转换为 iso-8859-2(抛光)