SQL查询消息投票

时间:2014-09-11 23:00:57

标签: php mysql

我需要为一个用户列出最佳投票的消息(用户ID:100)。

我正在尝试以下查询,但存在问题。

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)

注意:我的英语不好,对不起,我很抱歉。

1 个答案:

答案 0 :(得分: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