所以我特别密集我确定 - 但我正在努力学习PHP中的简单(mysql)SQL语句。
我有两张桌子:
entry
包含名称&比赛条目的细节。votes
包含时间戳,唯一ID和entry_id。 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';
有人可以告诉我如何最好地实现这个目标吗?
我的目标是返回前十个条目(通过投票数),并在返回数据中包含计数。
谢谢!
史蒂夫
答案 0 :(得分: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
答案 1 :(得分: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