2011-06-05 71 views
6

複雜的我,因爲我是SQL新手。複雜的SQL查詢,多對多

我有三個表 - PeoplesInterestsPeoples_Interests(許多一對多) - 這是連接方式如下:

People有很多Interests通過Peoples_Interests
Interest有許多Peoples通過Peoples_Interests

我需要向與他們最相似的人民提出建議,這些建議是基於類似興趣的金額。因此,對於示例

我對棒球,足球和凌空感興趣。我應該向另一位有儘可能多興趣的用戶提出建議。有3/3事件的人應該是我需要的,如果他們存在的話(如果不是 - 2/3等)。

所以我需要一個查詢,輸出將包括按利益相似性人民排序。

UPDATE: Db的結構:

興趣
ID
名字 - 字符串

人民
ID
電子郵件

Peoples_Interests
interests_id
peoples_id

謝謝。

+0

這將是,如果你easer詳細公佈了餐桌設計。在MySQL中選擇的將要運行得很慢的 – Hogan 2011-06-05 12:39:31

回答

3

就是這樣。

Select people.id, people.name, count(interest.id) 
from people 
left join people_interests on people.id = people_interests.peopleid 
left join interests on people_interests.interestid = interests.interest.id 
where interests.id in (select id from interests where interests.peopleid = @inputuserid) 
group by people.id, people.name 
order by count(interest.id) 

英語(這可能會或可能不會使其更清晰。)

  • 選擇此人的姓名和利益的數量,他們分享
  • 從百姓餐桌
  • 加入利益表,這樣的表
  • 只是我們試圖匹配的人的利益。
  • (組由人
  • 和order by相符的利益數。)

更新,而子查詢,但不太清楚

Select people.id, people.name, count(interest.id) 
from people 
left join people_interests on people.id = people_interests.peopleid 
left join interests on people_interests.interestid = interests.interest.id 
inner join interest i2 on (interests.id = i2.id and i2.people_id = @inputuserid) 
group by people.id, people.name 
order by count(interest.id) 
+0

。我會用內部加入興趣i2替換它(interests.id = i2.id和i2。people_id = @inputuserid)' – Johan 2011-06-05 12:48:06

+0

@johan是啊,它應該更新爲不使用子查詢,但我試圖讓他清楚。 – Hogan 2011-06-05 12:49:29

+0

我看到可理解性PoV如此+1。 – Johan 2011-06-05 12:52:16