【问题标题】:How can I join records where all of right table must be in set?如何加入必须设置所有正确表的记录?
【发布时间】:2016-09-13 18:46:44
【问题描述】:

我有一张表产品

通过product_features,产品具有许多功能

我想返回所有,同时具有功能 1 和功能 2 的产品,因此在这种情况下,典型的 LEFT JOIN 将不起作用 - 因为这将返回 产品具有功能 1 或功能 2。

谁能指出我正确的方向?

【问题讨论】:

  • 您可以使用两个内连接。

标签: mysql sql postgresql activerecord rails-activerecord


【解决方案1】:

您可以使用内部连接、分组和拥有

select p.* from products as p 
inner join product_features as pf on pf.product_id = p.id
inner join features as f on f.id = pf.feature_id 
where f.feature_id in ('feature1', 'feature2') 
group by product 
having count(*) =2;

答案是基于集合中的特征只出现一次这一事实

【讨论】:

  • 这假定功能“1”和“2”对于给定产品将只有一个 product_features 记录。可能是这种情况,但您应该确认这一点。
  • @PinnyM 查询应该适用于所有同时具有 ('feature1', 'feature2') 的产品..
  • 是的,但它也会返回条目(错误地),其中功能“1”有 2 条记录,而功能“1”没有记录。你可以使用COUNT(DISTINCT pf.feature_id) = 2 来解决这个问题。
  • @PinnyM 是的..当然..但这不是问题..我认为这些功能分布正确......可能是正确的OP评论..
  • 我不会假设任何事情 :) 但是,我确实在上面提到过,这可能是您所期望的。
【解决方案2】:

通过 OLAP 函数,您可以实现这一点。 以下查询统计了每种产品的不同特征。它返回所有具有两个特征的产品。

select pid, pname, fid
from (
  select t1.pid, t1.pname,t2.fid,count(distinct fid) over(partition by t1.pid, t1.pname) cnt from 
  products t1 left join product_features t2
  on t1.pid = t2.pid
) a
where cnt = 2
order by 1,2,3

【讨论】:

  • 我认为 OP 正在寻找符合两个特定功能的产品,而不是任何两个功能
  • 如果他能提供一些关于他期望的输出的样本数据,那就太好了
猜你喜欢
  • 1970-01-01
  • 2011-08-18
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 2023-03-14
相关资源
最近更新 更多