Database 获得多对多关系的提示性结果

Database 获得多对多关系的提示性结果,database,many-to-many,relational-database,Database,Many To Many,Relational Database,我有一张多对多的桌子 table tagged ( tid , pid ) // its a table to record all product that tagged with. 我有一个过滤器字段,它将接受许多标签,然后建议下一个可能标签的列表 交易进行得像 when the user filter with tid (1) The query will search all product tagged with tid 1 then also get others tid th

我有一张多对多的桌子

table tagged ( tid , pid ) 
// its a table to record all product that tagged with. 
我有一个过滤器字段,它将接受许多标签,然后建议下一个可能标签的列表

交易进行得像

when the user filter with tid (1)
The query will search all product tagged with tid 1
then also get others tid that also tagged in returned result
Then group all related tags and order it descendingly
这就是我想做的,但我迷路了。我已经研究并尝试了关系划分,但我认为我所尝试的要复杂得多

该示例基于提供的SQL FIDLE

样本1

Input = tid 1

Desired output 
return list of suggestion In descending which are tid -> 
2 (total amount 7) ,
5 (total amount 4) ,
4 (total amount 3) ,
3 (total amount 1)
样本2

Input = tid 1,2

Desired output 
return list of suggestion In descending which are tid -> 
5 (total amount 3) ,
4 (total amount 1) ,
3 (total amount 1)

这是我现在唯一的返回所有匹配产品的方法

我找到了错误的路径,我实际需要使用的是一个嵌套选择

解决方案

SELECT count(tid) FROM tagged 

WHERE pid IN (SELECT pid FROM tagged where tid = 1) AND tid != 1

GROUP BY tid
解释

SELECT count(tid) FROM tagged 

WHERE pid IN (SELECT pid FROM tagged where tid = 1) AND tid != 1

GROUP BY tid
第一

2rd


希望它能帮助别人

我挖错了路,我实际需要使用的是嵌套选择

解决方案

SELECT count(tid) FROM tagged 

WHERE pid IN (SELECT pid FROM tagged where tid = 1) AND tid != 1

GROUP BY tid
解释

SELECT count(tid) FROM tagged 

WHERE pid IN (SELECT pid FROM tagged where tid = 1) AND tid != 1

GROUP BY tid
第一

2rd


希望它能帮助别人

我也希望知道我应该去的术语…请添加一些样本数据result@gbn更新了我的问题,它遵循SQL FIDDLE中的表格,使用嵌套SELECT解决。我还想知道我应该使用的术语…请添加一些示例数据result@gbn更新了我的问题,它遵循SQL FIDDLE中的表,使用嵌套的select解决