2014-09-11 4 views
0

한 명의 사용자 (사용자 ID : 100)에게 가장 좋은 투표 메시지를 나열해야합니다.메시지에 대한 SQL 쿼리

다음 쿼리를 시도했지만 문제가 있습니다.

SELECT t.topics, m.msg_id, SUM(v.vote) AS totalvote 
FROM topics t, messages m, users u, votes v 
WHERE t.topic_id=m.topic_id 
and m.user_id=u.user_id 
and u.user_id='100' 
and v.user_id=u.user_id 
and v.user_id=m.user_id 
GROUP BY v.msg_id 
ORDER BY totalvote DESC 
LIMIT 0,10; 

어떻게하면됩니까?

내 데이터베이스 구조 (간체) :

------------------------- 
DB users 
------------------------- 
user_id (int) primary 

------------------------- 
DB topics 
------------------------- 
topic_id (int) primary 
topic (varchar) 

------------------------- 
DB messages 
------------------------- 
msg_id (int) primary 
topics_id (int) index 
user_id (int) index 

------------------------- 
DB votes 
------------------------- 
vote_id (int) primary 
msg_id (int) index 
user_id (int) index 
vote (int) 

참고 : 내 영어가 좋지 않아 내가 실수 죄송합니다.

+0

당신은'm.user_id = u.user_id AND v.user_id = u.user_id'를 가지고 있기 때문에 누군가 자신의 메시지로 한 투표 수만 계산합니다. – Barmar

+0

이 정보를 제공해 주셔서 감사합니다. – webmaster

답변

0

테이블에서 아무 것도 사용하지 않으므로 users 테이블과 조인 할 필요가 없습니다. votes의 조인은 msg_id이 아니고 user_id이 아니어야합니다. 당신은 메시지 작성자의 투표뿐만 아니라 모든 사람의 투표를 원합니다.

SELECT t.topic, m.msg_id, SUM(v.vote) AS totalvote 
FROM topics AS t 
JOIN messages AS m ON t.topics_id = m.topics_id 
JOIN votes AS v ON v.msg_id = m.msg_id 
WHERE m.user_id = 100 
GROUP BY m.msg_id 
ORDER BY totalvote DESC 
LIMIT 0, 10 
+0

Barmar 감사합니다. – webmaster