2010-08-14 14 views
5

2 tablo, 'interest' ve 'users_interests' var.MySQL'de benzer ilgi alanları nasıl sayılır

'users_interests' yalnızca userid ve interestid alanlarına sahiptir. 'ilgi alanlarının yalnızca bir id ve bir name vardır.

Sadece 3'ten fazla ilgi alanı kimliğine sahip olan userid'leri bulmam gerekiyor. Kendime Katılmanın söz konusu olduğu söylendi, ancak bunu işe almak için görünmüyor olabilir.

Birisi böyle bir şey işe yarayabilir ki:

SELECT 
     others.userid 
    FROM interests AS user 
    JOIN interests AS others 
     USING(interestid) 
    WHERE user.userid = 2 
    GROUP BY 
     others.userid 
    ORDER BY COUNT(*) DESC 

Ama onunla hiçbir şans yaşıyorum.

cevap

5
SELECT ui.userid, COUNT(*) AS common_interests 
FROM users_interests ui 
WHERE ui.interestid IN (
    SELECT ui2.interestid FROM users_interests ui2 WHERE ui2.userid = 2 
) 
AND ui.userid <> 2 
GROUP BY ui.userid 
HAVING common_interests > 3; 

Not kodunda iki yerde biz aramamızı dayanarak karar veriyorsun userid (2) şeklinde ortaya çıkışı

+0

İnanılmaz! Bunun için teşekkürler, bu güzel çalışıyor! – Ryan

2

genel numaralı telefondan 3'ten fazla ilgi ID'si belirttiniz, yani “en az 4”, yani? Bunu test etmedim yana

SELECT first1.userid, second1.userid 
FROM users_interests first1, users_interests second1, 
    users_interests first2, users_interests second2, 
    users_interests first3, users_interests second3, 
    users_interests first4, users_interests second4 
WHERE 
    first2.userid=first1.userid AND first3.userid=first1.userid AND first4.userid=first1.userid AND 
    second2.userid=second1.userid AND second3.userid=second1.userid AND second4.userid=second1.userid AND 
    first1.userid<>second1.userid AND 
    first1.interestid=second1.interestid AND 
    first2.interestid=second2.interestid AND first2.interestid<>first1.interestid AND 
    first3.interestid=second3.interestid AND first3.interestid<>first2.interestid AND first3.interestid<>first1.interestid AND 
    first4.interestid=second4.interestid AND first4.interestid<>first3.interestid AND first4.interestid<>first2.interestid AND first4.interestid<>first1.interestid 

, bunu anlarsanız nedenle, sadece kullanmak, içindeki hatalar olabileceğini hatırlatmak isteriz.

Aynı sayıda başka ilgi alanları için de aynı gerekiyorsa, bu soruyu dinamik olarak herhangi bir sayı için oluşturmak için kod yazabileceğinizi eminim. Ayrıca, isimlerine ihtiyacınız varsa, gerekli dört birleştirmeyi interests tablosuna ekleyebilecek ve ilgili sütunları SELECT maddesine ekleyebilirsiniz.

İlgili konular