php - MySQL: order by sum

845

I have article table

`id`,
`article_id`,
`stage_1_point`,
`stage_2_point`

I need top 10 articles based on

(stage_1_point+stage_2_point),

in the list and when i view any article i need to show its place. My question is how can show its place without using order by.

139

Answer

Solution:

USEORDER BY (stage_1_point+stage_2_point) DESC

So, It will be like

SELECT `id`,
`article_id`,
`stage_1_point`,
`stage_2_point`
FROM YOUR_TABLE ORDER BY (stage_1_point+stage_2_point) DESC
LIMIT 0,10

UPDATE

As OP stated, he/she needs to know the position of specific article.

SELECT * FROM (SELECT `id`,
`article_id`,
`stage_1_point`,
`stage_2_point`,
 @curRank := @curRank + 1 AS rank
FROM YOUR_TABLE, (SELECT @curRank := 0) r ORDER BY      
(stage_1_point+stage_2_point) DESC) TAB
WHERE `article_id`=10

Above query will return rows for article_id 10, which will have a columnRank which tells the position of the article.

776

Answer

Solution:

You can try below Query as below

Select 
    stage_1_point+stage_2_point as added_point,
    columnsid,
    article_id,
    stage_1_point,
    stage_2_point 
FROM tablename 
ORDER BY 1 desc 
Limit 0,10

This will sort data based on column one result and fetch top 10 results only.

People are also looking for solutions to the problem: php - CakePHP needs to set session for particular folders

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.