【问题标题】:Getting number of rows of joined table by condition on another通过另一个条件获取连接表的行数
【发布时间】:2014-04-03 03:49:46
【问题描述】:

我有两张表 products 和 products_to_categories

产品包含 - product_id - 名称 - 价格 (有多种产品) products_to_categories 包含 - product_id - category_id

我只需要条件满足时选择的行数

  1. 仅 ID 为“1”的类别 (category_id = '1');
  2. 仅限价格大于 100(价格 > 100)的产品

有什么想法吗?

【问题讨论】:

  • 不清楚您是需要两次计数,还是只需要一次计数。我的回答中的第一个查询返回两个不同的计数。

标签: php mysql


【解决方案1】:
select 
p.product_id,
p.name,
p.price
from products p
inner join products_to_categories  pc on pc.product_id = p.product_id
where 
pc.category_id = 1
AND p.price > 100

【讨论】:

  • 假设您的产品多于类别,MySQL 将希望从 products_to_categories 表开始并返回到 products 表,因此理想的索引将是 products(product_id, price)products_to_categories(category_id)。或者对于“覆盖索引”,使用products(product_id, price, name)
  • 是的,连接需要反转并从 products_to_categories 中选择
猜你喜欢
  • 1970-01-01
  • 2013-02-07
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-21
相关资源
最近更新 更多