开发者

Forming An SQL Query That Selects The Max Difference Of Two Fields

I'm trying to select a record with the most effective votes. Each record has an id, the number of upvotes (int) and the number of downvotes (int) in a MySQL database.

I know basic update, select, insert queries but I'm unsure of how to form a query that looks something like:

SELECT 开发者_JAVA百科* 
  FROM topics 
 WHERE MAX(topic.upvotes - topic.downvotes)


You are not using MAX() right.

Here is pretty fast query:

SELECT id, (upvotes - downvotes) AS popular  
FROM topics 
ORDER BY popular DESC LIMIT 1

To run an update:

UPDATE topics, 
    (here you put your select statement from above in parenthesis ) AS popular_query
SET topic.description = "I'm popular"
WHERE topics.id = popular_query.id

I just ran that on a table with 250,000 records (it's very similar - inventory usage - looking for a most popular part) and it took .203 of a second - on my dev machine - this is not even production server ( where it tppl 0.016 of a second)

UPDATE:

Yeah I didn't think about that possibility that you might have more than one top results.

SELECT GROUP_CONCAT(id) AS popular_ids, (upvotes - downvotes) AS popular 
FROM topics 
GROUP BY popular ORDER BY popular DESC  LIMIT 1

popular_ids - will contain popular records as a text field, that can be easily parsed out if you need to.


There may be more than 1 record that match that condition. In order to get them all you could do something like this in mysql:

SELECT * 
  FROM topics 
 WHERE upvotes - downvotes = (select MAX(upvotes - downvotes) from topics)


  SELECT (upvotes-downvotes) AS NetVotes, *
  FROM topics
  ORDER BY NetVotes DESC LIMIT 1


Does this do it for you?

SELECT *
FROM topics
ORDER BY topic.upvotes - topic.downvotes DESC
LIMIT 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜