在一个查询中执行此操作的方法

时间:2015-05-23 17:51:10

标签: mysql

我有一个看起来像这样的表

Table: Recommendations
Recommended_ID    Item_ID     Recommended_Item_ID    User_id
1                   1                   3                1
2                   1                   3                6
3                   1                   2                7
4                   2                   5                1

我希望我的SQL查询在伪代码中实现类似的东西:

SELECT recommended_item_id as f, COUNT(recommended_id) WHERE recommended_item_id = f AND item_id = 1, FROM `Recommendations` WHERE item_id = 1

To hopefully return:
Recommended_Item_ID   Recommended_Number_of_Times
3                              2
2                              1

基本上,我尝试获取为item_idx推荐的所有项ID,并返回推荐它们的次数以及ID。如何让我的SQL查询执行此操作?我已尝试过GROUP BY和HAVING,但问题是我不知道如何确保recommended_item_id等于我告诉SQL要搜索的initial_recommended_id。

2 个答案:

答案 0 :(得分:1)

select 
  Recommended_Item_ID,
  COUNT(recommended_id)
from `Recommendations`
where Item_ID = 1
group by Recommended_Item_ID

答案 1 :(得分:0)

查看group bywhere and group by

通过

尝试分组
select Recommended_Item_ID, count(*) as Recommended_Number_of_Times
from Recommendations
where Item_ID = X
group by Recommended_Item_ID
order by count(*) desc