2010-08-14 11 views
5

Mam 2 tabele, "zainteresowania" i "users_interests".Jak liczyć podobne zainteresowania w MySQL

"users_interests" ma po prostu pola userid i interestid. "Zainteresowania mają po prostu id i name.

Po prostu muszę znaleźć identyfikatory użytkownika, które mają więcej niż 3 identyfikatory zainteresowań. Powiedziano mi, że w grę wchodzi Self Join, ale nie mogę tego zmusić do działania.

Ktoś powiedział coś takiego może działać:

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 

ale mam szczęścia z nim.

Odpowiedz

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; 

Uwaga Występowanie z userid jesteśmy opierając nasze poszukiwania na (2) w dwóch miejscach w kodzie

+0

Amazing! Dziękuję za to, działa to pięknie! – Ryan

2

Powiedziałeś więcej niż 3 identyfikatory interesu wspólne, więc masz na myśli "co najmniej 4", prawda?

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 

Ponieważ nie testowałem tego, proszę pamiętać, że mogą być w nim błędy, więc używać go tylko wtedy, gdy go zrozumieć.

Jeśli potrzebujesz tego samego dla innych wspólnych interesów, jestem pewien, że możesz napisać kod, aby dynamicznie wygenerować to zapytanie dla dowolnej liczby. Ponadto, jeśli interesują Cię nazwy o nazwach, jestem pewien, że będziesz mógł dodać niezbędne cztery połączenia do tabeli interests i dodać odpowiednie kolumny do klauzuli SELECT.