我有很多像
这样的表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小提琴。
样本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 fiddle
答案 0 :(得分: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
2RD
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
希望能帮到别人。 Solution : nested select