Order by: Difference between two columns - php

i have a question about a sql query. I have two columns in table users:
Moneytotal and Moneythisweek
Right now i would like to order the results on difference.
How bigger the difference between Moneytotal and Moneythisweek the higher on the ranking.
Normally i use:
$lsel_rank = mysql_query("select * from users ORDER BY Moneytotal DESC");
$rank = mysql_fetch_array($lsel_rank);
But now i want to do something like:
lsel_rank = mysql_query("select * from users ORDER BY Difference between Moneytotal
AND Moneythisweek DESC");
Can anyone help me?

SELECT * FROM `users` ORDER BY Moneytotal - Moneythisweek DESC

Just simply use this
$lsel_rank = mysql_query("select *,'moneytotal - monethisweek' as difference from users ORDER BY difference DESC");

Option 1: (Doing calculation in orderby)
SELECT * FROM `users` ORDER BY (Moneytotal - Moneythisweek) DESC;
Option 2: (Using numbered index in order by and calculating the difference and make available in the select query's resultset
SELECT (Moneytotal - Moneythisweek) difference, a.* FROM `users` a ORDER BY 1 DESC;

Related

PHP SQL Query to get the most common value in the table

I'm trying to have my query count the rows and have it return the most common name in that list, then from that it counts how many times that name appears and outputs the name and the amount of times its there
This is the code I'm using:
$vvsql = "SELECT * FROM votes WHERE sid=? ORDER BY COUNT(*) DESC LIMIT 1";
$vvresult = $db->prepare($vvsql);
$vvresult->execute(array($_GET['id']));
$vvcount = $vvresult->rowCount();
foreach ($vvresult->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['username'];
echo $vvcount;
}
However, it just displays the first username in the table and counts up the entire table. I'm pretty new to this so I'm sorry if this is a bad post or if it didn't make much sense.
You would seem to want:
SELECT name, COUNT(*) as cnt
FROM votes
GROUP BY name
ORDER BY COUNT(*) DESC
LIMIT 1;
Note the GROUP BY. You may also want to filter by sid but your question makes no mention of that.
select username, count(*) as c
FROM votes
GROUP BY username
ORDER BY c DESC

ORDER BY RAND() returns duplicates

I tried using distinct as well and it returns duplicates.
$cubes = mysql_query("SELECT distinct * FROM posts ORDER BY RAND() $limit ") or die(mysql_error());
I just want to take my posts table... and return it in a random order without duplicates.
Select only the distinct id's you need, e.g.
SELECT distinct id FROM posts ORDER BY RAND() $limit
Distinct works over 'all' rows you select, so if you (for example) have a unique timestamp field, chances are you'll return every single row.
Are you sure that you want to execute a SELECT DISTINCT * FROM ... and not just a SELECT DISTINCT column_name FROM ... ?
See the SQL DISTINCT STATEMENT doc for more infos.

Return a random row without using ID, MySQL

I am looking for a better way of doing this:
SELECT * FROM $tbl_name WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM $tbl_name ) ORDER BY id LIMIT 1;
It is slow and isn't very random, I get the same result every 10 or so query's.
This selects a random row from the table regardless of its ID.
So far I have this:
// Get amount of rows in database
$result = mysql_query("SELECT * FROM $tbl_name");
$num_rows = mysql_num_rows($result);
// Generate random number
$random_row = rand(1, $num_rows);
But I don't know how to get a certain row.
I do not mean
SELECT * FROM $tbl_name WHERE id = $random_row
Because my database has gaps in the ID column so it would sometimes fail.
Has anyone got script that can get a random result from a MySQL database without replying on IDs and is super fast? (the database contains about 20000 rows)
SELECT * FROM $tbl_name WHERE 1 ORDER BY RAND() LIMIT 1;
20,000 rows isn't really that much, the above should be fast enough.
Juhana is right by the book: "ORDER BY RAND() LIMIT 1", and of course 20k isn1t that much.
Other option will be with subselects:
SELECT [fields]
FROM myTable,
(SELECT FLOOR(MAX(myTable.id) * RAND()) AS randId FROM myTable) AS someRandId
WHERE myTable.id = someRandId.randId
discussed here
(please avoid select * when it`s unnecessary)
After some searching though the comments on the link Adi sent, I have found a decent solution.
SELECT * FROM $tbl_name T JOIN (SELECT CEIL(MAX(ID)*RAND()) AS ID FROM $tbl_name) AS x ON T.ID >= x.ID LIMIT 1;
Source: wanderr.com/jay/order-by-slow/2008/01/30
Seems to be very fast and very random!

How to select the last n row in MySQL?

with this code I select the first 30 row of the table:
SELECT * FROM `table` LIMIT 0 , 30
But how to select the last 30, without changing the order?
It looks like everyone is missing this part:
But how to select the last 30, without changing the order?
First of all, clearly there is no order in the query provided. Assuming the order is ascending on some field this would be the query #DannyFox meant:
SELECT * FROM T
ORDER BY val
LIMIT 0 , 30
Now imagine we have simplified data, such as a, b, c, d, e and that we want only 3 rows instead of 30:
SELECT * FROM T
ORDER BY val
LIMIT 3
If this returns: a, b, c, d, e in each row, then he would expect to get c, d, e in that order. The query everyone is providing:
SELECT * FROM T
ORDER BY val desc
LIMIT 3
Would return e, d, c. The problem with this is that it's actually changing the original order, and the OP say he didn't want to change the order. So technically, the query that would result in c, d, e is:
select * from (
select * from t
order by val desc
limit 3
) s
order by val
Which actually changes the order twice, getting the original order back.
Since you are trying to avoid ordering, then the solution would be to apply it twice.
SELECT *
FROM (
SELECT *
FROM `table_name`
ORDER BY `column_name` DESC -- maybe id?
LIMIT 0, 30
) `table_aliase`
ORDER BY `column_name` ASC
First you need to specify an order:
SELECT * FROM table
ORDER BY some_id ASC -- ascending order
LIMIT 30
If that query returns the first 30 columns, this one will return the last 30:
SELECT * FROM table
ORDER BY some_id DESC -- descending order
LIMIT 30
If you have an auto incremental key/column, say id then here's an example
SELECT * FROM `table` ORDER BY id DESC LIMIT 0 , 30;
Maybe this will work: select * from table WHERE id > ((SELECT MAX(id) from table) - 30);
Nothing is said about an order, so you can not use ORDER BY.
There is a way to get records from a given point, but for that you need to know how many records there are, then use this counted value to provide the limits
SELECT COUNT(*) AS counted FROM table
SELECT * FROM table LIMIT (counted-30),30
Here's my method used with PHP:
$query = "SELECT * FROM table ORDER BY id DESC LIMIT 3";
$res = mysql_query($query);
$results = array();
while($row = mysql_fetch_assoc($res)){
$results = $row[field];
}
// Back to original order based from DB
$results = array_reverse(results);

Get Latest Entry from Database

How can I get the latest entry by the latest DATE field from a MySQL database using PHP?
The rows will not be in order of date, so I can't just take the first or last row.
You want the ORDER BY clause, and perhaps the LIMIT clause.
$query = 'SELECT * FROM `table` ORDER BY `date` DESC LIMIT 1';
SELECT * FROM [Table] ORDER BY [dateColumn] DESC
If you want only the first row:
In T-SQL:
SELECT TOP(1) * FROM [Table] ORDER BY [dateColumn] DESC
In MySQL:
SELECT * FROM `Table` ORDER BY `dateColumn` DESC LIMIT 1
You don't have a unique recordid or date revised field you could key in on? I always have at least an auto incrementing numeric field in addition to data created and date revised fields. Are you sure there is nothing you can key in on?
SELECT * FROM table ORDER BY recno DESC LIMIT 1;
or
SELECT * FROM table ORDER BY date_revised DESC LIMIT 1;
So the PHP call would be:
$result = mysql_query("SELECT * FROM table ORDER BY date_revised DESC LIMIT 1");
-- Nicholas
You can use a combination of the LIMIT and ORDER BY clauses.
For example:
SELECT * FROM entries ORDER BY timestamp DESC LIMIT 1

Categories