0

So I'm being particularly dense I'm sure - but I'm struggling with what should be a simple (mysql) SQL statement in PHP.

I have two tables:

  • entry containing the name & details of a competition entry.
  • votes containing a timestamp, unique ID, and entry_id. Each row with the entry_id matching the id of an entry represents one vote for that person's competition entry.

The rough Db Structures are:

entry table:

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

votes table:

|id|entry_id|created|deleted|

My attempts (various rewrites, probably too tired!) have resulted in just one row being returned.

My latest attempt:

$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';

Can someone give me a steer on how best to achieve this?

I'm aiming for the top ten entries returned (by vote count) with the count included in the return data.

Thanks!

Steve

4

2 に答える 2

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

?

于 2013-09-29T21:06:15.933 に答える
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
于 2013-09-29T21:10:44.473 に答える