2013-10-17 62 views
0

我有這樣的架構(只是嘗試,所以如果你有改進的建議,我所有的耳朵):MySQL - 如何通過投票總數完成加入和訂購?

mysql> describe contest_entries; 
+---------------+----------------+------+-----+---------+----------------+ 
| Field   | Type   | Null | Key | Default | Extra   | 
+---------------+----------------+------+-----+---------+----------------+ 
| entry_id  | int(10)  | NO | PRI | NULL | auto_increment | 
| member_id  | int(10)  | YES |  | NULL |    | 
| person_name | varchar(10000) | NO |  | NULL |    | 
| date   | date   | NO |  | NULL |    | 
| platform  | varchar(30) | YES |  | NULL |    | 
| business_name | varchar(100) | YES |  | NULL |    | 
| url   | varchar(200) | YES |  | NULL |    | 
| business_desc | varchar(3000) | YES |  | NULL |    | 
| guid   | varchar(50) | YES | UNI | NULL |    | 
+---------------+----------------+------+-----+---------+----------------+ 
9 rows in set (0.00 sec) 

mysql> describe contest_votes; 
+------------------+---------+------+-----+---------+----------------+ 
| Field   | Type | Null | Key | Default | Extra   | 
+------------------+---------+------+-----+---------+----------------+ 
| vote_id   | int(10) | NO | PRI | NULL | auto_increment | 
| user_id   | int(10) | NO |  | NULL |    | 
| contest_entry_id | int(10) | NO | MUL | NULL |    | 
| vote    | int(7) | NO |  | NULL |    | 
+------------------+---------+------+-----+---------+----------------+ 

,我試圖拉數據排行榜,排序由得票最多的結果。我會怎麼做?我能夠做左連接部分,但查詢的總和和排序部分令我感到困惑。

謝謝!

+0

既然你不知道怎麼弄的總和,我聽說好東西的書,自學SQL是10分鐘。就您的架構而言,person_name可能不應該位於contest_entries表中。你應該能夠從另一個表格的member_id字段獲得它。另外,在contest_entries中guid字段的用途是什麼? –

+0

@DanBracuk guid是爲了避免重複的條目。我正在嘗試不將其輸入到member_id以獲得唯一性,以便我不必強制人員進行註冊。 – Genadinik

+0

在'contest_votes'中每投票一行還是隻有一行?'contest_entry_id'或'user_id'只有一行? – Litmus

回答

1
SELECT entry_id 
FROM contest_entries 
LEFT OUTER JOIN contest_votes ON entry_id = contest_entry_id 
GROUP BY entry_id 
ORDER BY SUM(vote) DESC 
1
select e.entry_id, sum(v.vote) as votes 
from contest_entries e 
left join contest_votes v on e.entry_id = v.contest_entry_id 
group by e.member_id 
order by votes desc