【问题标题】:Many to many relationship query with only attribute known [duplicate]仅具有已知属性的多对多关系查询[重复]
【发布时间】:2014-03-12 04:43:44
【问题描述】:

我有 3 个表,TableA、TableB 和 TableAB(多对多表)。

参见下面的 TableAB 示例:

TableAB

id_attribute | id_product_attribute
14 | 18
14 | 19
16 | 10
16 | 12
16 | 16
16 | 18
16 | 20
16 | 22
16 | 24
16 | 26

在这个表中,我有来自 TableA 的 id_attribute 和来自 TableB 的 id_product_attribute。

如果我想找出同时具有 id_attributes 14 和 16 的 id_product_attribute,我应该怎么做?

基本上,我有 id_attributes 的组合,我正在寻找包含所有这些的特定 id_product_attribute。

在上面的示例中,只有 product_attribute 18 具有属性 14 和 16。我的第一个查询将找出所有属性。我现在遇到的这个问题是从这个表中确定它是哪个产品属性。

谢谢。

【问题讨论】:

标签: mysql sql


【解决方案1】:
select 
   count(ab1.id_product_attribute),ab1.id_product_attribute,ab1.id_attribute
from ab ab1
join ab ab2
on ab1.id_product_attribute = ab2.id_product_attribute
where ab1.id_attribute in (14,16) 
and ab2.id_attribute in (14,16)
group by ab1.id_product_attribute,ab1.id_attribute
having count(ab1.id_product_attribute) > 1;

SQL 小提琴: http://sqlfiddle.com/#!2/007eb/13

【讨论】:

    【解决方案2】:

    你想要一个自我加入。

    select distinct ab1.id_product_attribute
    from   tableAB ab1
    join   tableAB ab2 on ab1.id_product_attribute = ab2.id_product_attribute
    where  ab1.id_attribute = 14
    and    ab2.id_attribute = 16
    

    这首先会创建一个仅包含 id_attribute 14 的 tableAB 选择。然后是另一个仅包含 id 16 的选择。然后将这两者连接起来以仅查找匹配项。

    【讨论】:

    • 如果TableAB (id_attribute, id_product_attribute) 上有UNIQUE 约束,则不需要DISTINCT
    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2023-02-13
    • 2013-05-03
    • 1970-01-01
    相关资源
    最近更新 更多