2017-01-18 109 views
0

基本上我想訂單記錄

Select * from x 
JOIN y 
on x.id = y.x_id 
where y.tag_id in (1, 2, 3, 4) order by [the amount of hits of y.tag_id] 

所以

說Y可以是:

id | x_id | tag_id 
1 | 55 | 2 
2 | 55 | 3 
3 | 66 | 1 

我要作記錄x.id = 55排序上述x.id = 66 55具有2次命中(2和3),而66只具有一個撞

回答

1

,可以看到每X_ID命中計數在子查詢中,加入它機智h X表格並按計算的計數對結果進行排序。

Select * from x 
JOIN y 
on x.id = y.x_id 
inner join (
    select x_id, count(*) cnt 
    from y 
    group x_id 
) t on x.id = t.x_id 
where y.tag_id in (1, 2, 3, 4) 
order by t.cnt desc; 
1

計數傳遞tag_id匹配x_idOrder by

SELECT * 
FROM x 
     JOIN y 
     ON x.id = y.x_id 
     JOIN (SELECT x_id, 
        Count(*) hit_cnt 
      FROM y 
      WHERE y.tag_id IN (1, 2, 3, 4) 
      GROUP BY x_id) ct 
     ON ct.x_id = y.x_id 
ORDER BY hit_cnt DESC 

使用它,而計算應用的過濾器是很重要的,因爲我們需要統計x_id's的匹配tag_id's