2013-09-29 50 views
0

所以我非常密集,我敢肯定 - 但我正在努力應該在PHP中使用簡單的(mysql)SQL語句。SQL - 根據單獨表中相關條目的計數來選擇記錄

我有兩個表:

  • entry包含名參賽的&細節。包含時間戳,唯一ID和entry_id的
  • votes。 entry_id與條目ID相匹配的每一行代表該人競爭條目的一票。

粗糙Db的結構是:

條目表:

|id|name|email|created|deleted| [last two cols being datetime stamps] 

票表:

|id|entry_id|created|deleted| 

我嘗試(!各種重寫,可能太累了)導致只有一行正在返回。

我的最新嘗試:

$sql = 'SELECT 
     s_id, 
     count(sv.s_id) as count 
    FROM 
     'vote AS sv 
    LEFT JOIN 
     'entry AS se on sv.entry_id = se.id 
    WHERE 
     sv.deleted = "0000-00-00 00:00:00" 
    AND 
     se.deleted = "0000-00-00 00:00:00" 
    ORDER BY 
     count DESC 
    LIMIT 
     10'; 

有人可以給我就如何更好地實現這一目標轉舵?

我打算將返回數據中包含的計數返回給前10位(通過投票計數)。

謝謝!

史蒂夫

+0

您在'vote'和'entry'之前的SQL字符串中有一些額外的引號。他們是在原始代碼? – Barmar

+0

不 - 當我想到複製和粘貼時有些怪異。這是我缺乏的一組條款。 – steve

回答

2

如何

SELECT e.id, COUNT(v.id) AS numVotes 
FROM entry AS e 
JOIN vote AS v ON v.entry_id = e.id 
WHERE e.deleted = "0000-00-00 00:00:00" 
AND v.deleted = "0000-00-00 00:00:00" 
GROUP BY e.id 
ORDER BY numVotes DESC 
LIMIT 10 

+0

謝謝!我缺少一個GROUP BY子句。 一個肯定的跡象,我應該忘記這個截止日期,並抓住一些睡眠。謝謝 - 願意接受這個答案。 – steve

0
select 
     e.*, 
     cnt 
from 
     entry e, 
(
     select 
       entry_id, 
       count(*) cnt 
     from 
       votes 
     where 
       deleted = "0000-00-00 00:00:00" 
     group by 
       entry_id 
     order by 
       count(*) desc 
     limit 10 
) c 
where 
     c.entry_id = e.id and 
     e.deleted = "0000-00-00 00:00:00" 
order by 
     cnt desc 
相關問題