简体   繁体   中英

Mysql creating a top 10

I have big database full of information and I use the following Query to select the information I need.

$query = mysql_query("SELECT * FROM db WHERE model LIKE '%iphone 4%' AND model LIKE '%16GB%'") or die(mysql_error());
while ($row = mysql_fetch_assoc($query)) {

This leaves me with about 250 results, I use a while loop and display a [tr] for each result. Now I want to create a top ten. This is what I came up with:

$monthavg = ($row['price_shipping'] / $row['abo_time']) + ($row['price'] / $row['abo_time']) + $row['abo_price'];

So now I can echo $monthavg and its a good way to get a top ten. What I would rather like to do is just show 10 rows [tr] with the lowest $monthavg. But I already echo'd a table to the screen.

My question: Can I create a top 10 of my database and echo just those 10 results?

You already have the answer, just redo the query with your calculation as column, then order by that column and limit it to first 10 results

SELECT *, (price_shipping / abo_time + price / abo_time + abo_price) AS month_avg 
FROM db WHERE model LIKE '%iphone 4%' AND model LIKE '%16GB%'
ORDER BY month_avg ASC LIMIT 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM