开发者

PHP/MYSQL query ranking using secondary tables

Working with a ranking algorithm, but I'm getting frustrated with the multiple database calls and data gyrati开发者_如何学Pythonons i'm having to go through to calculate the rank of a specific item, output it in to an array, and then sort by the rank value. Is it possible in MySQL to calculate the rank of a given row based on the data found in other tables?

SELECT key_value FROM table;

Now with the result set I need to rank each item based on various other tables information about those items. So if the output was -

|key_value|
|abcd1    |
|abcd2    |
|abcd3    |

Then based on 'abcd1' values in 3 other tables, I need to rank each entry based on the value divided by total and return the rank and then output it. Is there a way to do all this in a single SQL statement? I've thought about setting up some sql variables and storing different calls and then doing the calculation, but I'm still not sure how you would assign that to the SELECT statements output and rank it accordingly. I'm good with PHP, but i'm kind of a MySQL n00b.

This is probably confusing the way I'm describing it - I can answer more questions to help better explain what I'm trying to do.

Basically each row returned in the original statement is really only relevant to each user based on information stored about that object in 3 other tables. Need to know the best way to use the data in the 3 other tables to rank the relevancy of the data from the first table.


The key here is that you need to JOIN your other tables, then ORDER BY some expression on their fields.

SELECT key_value 
FROM table
LEFT JOIN table_b on table_b.field = table.key_value
LEFT JOIN table_c on table_c.field = table.key_value
LEFT JOIN table_d on table_d.field = table.key_value
ORDER BY table_b.some_field DESC, (table_c.another_field / table_d.something_else) ASC
;

Depending on the join conditions, you may need to GROUP BY table.key_value or even use subqueries to attain the appropriate effect.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜