1

我有一个多对多的桌子,比如

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 fiddle。

样品 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)

这是我现在拥有的唯一返回所有匹配的产品SQL 小提琴

4

1 回答 1

1

我挖到了错误的路径,我真正需要使用的是嵌套选择

解决方案

SELECT count(tid) FROM tagged 

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

GROUP BY tid

解释

第一

SELECT pid FROM tagged where tid = 1 //will return full list of product tagged with 1

第 2 次

SELECT count(tid) FROM tagged WHERE pid IN (1st)
AND tid != 1
//get all tid with return product in 1st query exclude selected tag
GROUP BY tid
//group it so i can sort it

希望它帮助别人。解决方案:嵌套选择

于 2013-06-13T09:11:22.743 回答