steve
steve

Reputation: 2519

SQL - selecting records based on a count of related entries in a separate table

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:

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

Upvotes: 0

Views: 362

Answers (2)

Lajos Veres
Lajos Veres

Reputation: 13725

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

Upvotes: 0

TheWolf
TheWolf

Reputation: 1385

How about

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

?

Upvotes: 2

Related Questions