选择内部加入

时间:2018-05-22 15:14:22

标签: mysql sql join mariadb

我有一张表格,表示优惠,个人资料和技能之间的三元关系。

任何给定的优惠都可以拥有多个个人资料,并且可以提供超过1个技能。

这样的事情:

ternary_relationship表

id_Offer    -   id_Profile  -   id_Skill
1           -   1           -   1
1           -   1           -   2
1           -   1           -   3
1           -   2           -   1
2           -   1           -   1
2           -   1           -   2
2           -   1           -   3
2           -   2           -   1

优惠表

Offer   -   business_name
1       -   business-1
1       -   business-1
1       -   business-1
1       -   business-1
2       -   business-2 
2       -   business-2 
2       -   business-2 
2       -   business-2 

我希望通过个人资料进行查询过滤,并且只计算一次提议,无论它与多少技能相关联。

我正在执行以下查询:

SELECT business_name, COUNT(*)
FROM Offer INNER JOIN
     ternary_relationship
     ON Offer.id_Offer = ternary_relationship.id_Offer AND
        id_Profile =  '1'
 GROUP BY business_name
 ORDER BY COUNT(*) DESC;

我看过several possible解决方案,但我无法让任何人为我的案件工作。当我为两个名字分组id_Offer时,或者当我只按id_Offer过滤它时,它也都可以。我总是在某处获得重复的条目。

1 个答案:

答案 0 :(得分:0)

您可以执行JOINS并使用DISTINCT

进行一次计数
select o.business_name, count(distinct tr.id_Offer) counts
from Offer o inner join 
     ternary_relationship tr on 
     o.Offer = tr.id_Offer 
where tr.id_Profile = ?
group by o.business_name
order by 2 desc;