按最高投票计数对帖子排序?

时间:2011-12-18 17:48:36

标签: php sql

SELECT 
links.id, 
links.url, 
links.user_id, 
links.title, 
links.description, 
links.nsfw, 
links.posted, 
links.category_id,

votes.vote
votes.vote_date

FROM links 

INNER JOIN votes
ON votes.link_id = links.id

ORDER BY (I want to sort by the count of votes on the links) DESC

如果我想通过投票对我的链接/帖子进行排序,那么我怎么能用这个SQL来做呢? 具有最高投票数的链接首先显示。

4 个答案:

答案 0 :(得分:1)

您想要分组。试试这个:

SELECT 
  links.id, 
  links.url, 
  links.user_id, 
  links.title, 
  links.description, 
  links.nsfw, 
  links.posted, 
  links.category_id
FROM 
  links 
  INNER JOIN votes ON votes.link_id = links.id
GROUP BY links.id
ORDER BY COUNT(votes.id) DESC

我没有测试它(因为我没有你的数据集),但它应该或多或少是正确的。

答案 1 :(得分:0)

  1. 按链接ID分组并选择投票数

    SELECT
        count(*) as votecount,
        links.id, 
        links.url, 
        links.user_id, 
        links.title, 
        links.description, 
        links.nsfw, 
        links.posted, 
        links.category_id,
        votes.vote
        votes.vote_date
    FROM links 
    INNER JOIN votes
        ON votes.link_id = links.id
    GROUP BY links.id
    
  2. 2。)将它包装在superquery中进行排序

    SELECT * FROM (
        <as above>
    ) AS baseview
    ORDER BY votecount DESC
    

答案 2 :(得分:0)

您可以使用子查询:

SELECT links.id, links.url, votes.vote, votes.vote_date
FROM links
INNER JOIN votes ON votes.link_id = links.id
INNER JOIN (
    SELECT links.id AS link_id, COUNT(votes.id) AS num_votes
    FROM links
    INNER JOIN votes ON votes.link_id = links.id
    GROUP BY links.id
) AS votes_per_link ON links.id=votes_per_link.link_id
ORDER BY votes_per_link.num_votes DESC

答案 3 :(得分:0)

由于我不明白你要求的这些行为,我在这里发布不同案例的解决方案:

获取链接,按最高投票顺序:

SELECT votes.link_id, links.url, MAX(votes.vote) AS maxvote
FROM votes INNER JOIN links ON links.id = votes.link_id
GROUP BY votes.link_id ORDER BY `maxvote` DESC;

获取链接,按平均投票顺序:

SELECT votes.link_id, links.url, AVG(votes.vote) AS avgvote
FROM votes INNER JOIN links ON links.id = votes.link_id
GROUP BY votes.link_id ORDER BY `avgvote` DESC;

获取链接,按投票数排序:

SELECT votes.link_id, links.url, COUNT(votes.vote) AS cntvotes
FROM votes INNER JOIN links ON links.id = votes.link_id
GROUP BY votes.link_id ORDER BY `cntvotes` DESC;

以最高票数获得投票:

SELECT links.id, links.url, votes.vote
FROM links INNER JOIN votes ON links.id = votes.link_id
ORDER BY votes.vote DESC;

(我省略了一些缩短查询的字段,当然可以随意添加它们。)