mysql_fetch_row and ORDER BY - what am I doing wrong? - mysql

Sorry for the vague title, but I've been trying to nail this for a week and have run out of ideas.
Table: name: scores
id name password intuition
(int, varchar, varchar, int)
(5 rows with made-up values)
The PHP:
$userResult = mysql_query("SELECT `intuition` FROM `scores` ORDER BY `intuition` DESC LIMIT 4,1");
if($userResult ==NULL)
{ die(mysql_error());
}else
{ if($userResult ==FALSE)
{ die("ranking query failed, sorry");
}else
{ if(mysql_num_rows($userResult) ==NULL)
{ die("No ranking results found.");
}else
{ $queryRow = mysql_fetch_row($userResult);
$topIntuition = $query_row['intuition'];
die("queryRow =$queryRow; topIntuition =$topIntuition");
}
}
}
Output:
query row =Array; topIntuition =
where topIntuition should be the fifth highest result, currently the integer 2. What am I doing wrong?
EDIT: $query_row[<name of row>] does not work, but $query_row[0] does.

LIMIT 4, 1 will return the fifth highest result (as LIMIT 0, 1 returns the first).
Regardless, mysql_fetch_row returns an array with keys that are numeric - try $queryRow[0];
Alternatively, you can switch to mysql_fetch_array or mysql_fetch_assoc.

Related

select top 10 in total sum in mysql table

I have MySQL table as bellow
id, name, postcode, address
in my, table postcode will be like this
AX12 3NB
NB76 5BQ
AX23 6NB
AX87 6CZ
I want to get top 10 Postcode in total like postcode start with AX appear 3 times
I have Laravel project and want to do in this syntax
DB::table('users')
I want to get the total number of any postcode first 2 letters and only the top 10 records.
Thanks
First, get all the records, then use PHP to sort and reduce the size of the array. The best way to do this is with a raw query, but since you stated above that you don't want to use a raw query, this is a quick way to handle it.
$users = DB::table('users')->get();
$postcodes_array = [];
foreach ($users as $user) {
$first_two = substr($user->postcode, 0, 2);
if (isset($postcodes_array[$first_two])) {
$postcodes_array[$first_two] += 1;
} else {
$postcodes_array[$first_two] = 1;
}
}
arsort($postcodes_array);
$postcodes_array = array_slice($postcodes_array, 0, 10);

I wan to check that is my sql command containing the inputted data or not

I have two rounds "first and knock-out".Only the 4 team can go to knock-out round if they got the highest point on first round. Now firstly, I want to select that 4 team from first round and then check whether the inputted team is on the selected 4 team or not. Take a look to my code(So far i tried)
[In this image the two teams are marked should be exclude but when i giving condition it doesn't exclude those two teams]
$matches= new Match();
$matches->team1 = $request->input('team1');
$matches->team2 = $request->input('team2');
$ko = DB::select('SELECT * FROM points WHERE round="first" ORDER BY points DESC , run_rate DESC LIMIT 4');
if($ko == $matches->team1 || $ko == $matches->team2) {
$matches->round = "ko";
} else {
$matches->round = "first";
}
Screenshot of $kos after update.
First of all, $ko doesn't contain the results of the query until you pass it a closure, in this case ->first().
$ko = DB::select('SELECT * FROM points WHERE round="first" ORDER BY points DESC , run_rate DESC LIMIT 4')->first();
Next, you need to compare the value of $ko->team to $matches->team1 or $matches->team2:
if($ko->team == $matches->team1 || $ko->team == $matches->team2) {
...
}
Lastly, some clean up. The DB query can be simplified to use Eloquent syntax, instead of a raw SELECT:
$ko = DB::table("points")
->where("round", "=", "first")
->orderBy("points", "DESC")
->orderBy("run_rate", "DESC")
// ->limit(4) // Removing this; incompatible with `->first()`
->first();
There's another logic error; if you need to limit(4), then you can't use ->first(), you'd have to use ->get(), which then creates a Collection, which can't be compared to $matches unless you loop:
$kos = DB::table("points")...->get();
$matches->round = "first";
foreach($kos AS $ko){
if($ko->team == $matches->team1 || $ko->team == $matches->team2) {
$matches->round = "ko";
break;
}
}
All in all, you need to reexamine what you're trying to do and read up on the Eloquent syntax, how to execute queries and return results, how to loop, access properties and compare those results, etc.
Edit: Since you're looping and comparing, set the default value of $matches->round to "first", then, while looping, if the compare condition is true, override $matches->round to "ko" and break out of the loop.

Finding the id whose average sum is maximum compared to other id

I have a MySQL table named "Rating" which contains (id, rateable_id, rating, user_id) columns. rateable_id is the id of a record which is rated and rated score is stored in rating (star rating). All I want to do is to find particular rateable_id (grouped by) whose sum average is maximum among other rateable_id.
In the above sample table , i should get rateable_id = 26 because its rating is max ((3+3)/2) = 3 as compared to other rateable_id.
raw sql or eloquent any preferred.
Edit: Sorry to mention but i have done roughly in not standard way Anyway it returns the answer but i am looking using nested select answer. averageRating is willvincent package for counting avg sum of rating. $popular_post returns the id whose average rating sum maximum.
$posts = "App\Opportunity"::all(); //where(createdate < 1month)
$i=11;
$cr=0;
$pr=0;
$mi = 0; //max index
$maxR=0; //max rating value
for($i=0; $i< count($posts); $i++)
{
$cr = $posts[$i]->averageRating; //current rating
if($cr)<br>
{
if($cr > $maxR)
{
$maxR = $cr;
$mi = $i;
}
}
else
{
// echo "skip<br>";
}
}
$popular_post = ($posts[$mi]->id);
You are going to need 2 selects:
SELECT MAX(rating) rating, rateable_id FROM (
SELECT AVG(rating) rating, rateable_id FROM table GROUP BY reateble_id
) GROUP BY rateable_id ORDER BY rating LIMIT 1
I think this will help you little bit.
$ratings = Rating::all()->groupBy('rateable_id');
$topList = [];
foreach($ratings as $key => $value){
$topList[$key] = ($value->sum('rating')) / count($value);
}
arsort($topList); //sort the array by top values
$max_rateable_id = key($topList); //key of first item of the array
$max_rating = reset($topList); //value of first item of the array
$both = [$max_rateable_id => $max_rating]; //key and value of the first item of the array

How return only value change from a mysql query without using php?

I have 2 mysql tables with 500.000 items
first with items price, items id, and ticket number
second with ticket_number, date of sales and total_price of ticket
by now i use this query
SELECT items.pri,ticket.date,items.crd,items.plu
FROM items ,ticket
WHERE
(items.crd = 25 OR items.crd = 30) AND items.SeqNbr = ticket.SeqNbr
then in php:
$val_1 = array();
$price1 = 0;
while($row = mysql_fetch_array($query))
{
if($row['crd'] == 25)
{
$prix = $row['pri'];
if($prix != $price1)
{
$val_1[] = array( (int)$row['date']*1000,(float)$row['pri']);
$price1 = $prix;
}
}
}
return:
[[1388552879000,1.519],[1389136505000,1.498],[1392420222000,1.514],[1394667334000,1.499],[1395373887000,1.478],[1395963467000,1.499],[1396649284000,1.52],[1397513210000,1.542],[1398384245000,1.556],[1399347974000,1.536],[1400910286000,1.553],[1403216692000,1.58],[1405029076000,1.563]]
goal is obtain an array with price change and date to build a charts of price fluctuation.
but with more than 500.000 records this is extremly slow (15 sec)
is there any possibilities to build mysql query that return the same array ?
Thanks
First you need to check where is the bottleneck, on the query or on the loop.
If it is on the query, check if you have the right index. If not, try adding index for the fields items.crd, items.SeqNbr and ticket.SeqNbr.

Mysql get count of rows for each day

My Current query is:
SELECT DISTINCT DATE(vote_timestamp) AS Date, COUNT(*) AS TotalVotes FROM `votes`
WHERE vote_target_id='83031'
GROUP BY DATE(vote_timestamp) ORDER BY DATE(vote_timestamp) DESC LIMIT 30
(line breaks separated for readability)
Where vote_timestamp is a time for each "vote", Count(*) is the count for that day, and vote_target_id is the specific target of the vote.
Currently, this works for all days in which the target has at least one "vote", but I would like it to also return TotalVotes as 0 for days where there are no votes, rather than having no row at all.
Can this (and how?) be done in MySQL or PHP? (either is fine, as it is futher processed by PHP so either code can be used).
Thank you
The problem is how to generate records for days that have no rows. This SO question has some approaches.
Looking at that solution, it looks like for me it's much simpler to do this quick fix that sorta works.
$result = mysql_query($sql) or die('Internal Database Error');
if (mysql_num_rows($result) == 0) { return false; }
while($row = mysql_fetch_assoc( $result )) {
$votes[$row['Date']] = $row['TotalVotes'];
}
// fill 0s with php rather than using mysql
$dates = array_keys($votes);
for ($t = strtotime($dates[count($dates)-1]); $t <= time(); $t +=86400) {
$date = date('Y',$t).'-'.date('m',$t).'-'.date('d',$t);
if (!array_key_exists($date,$votes)) {
$votes[$date] = 0;
}
}
thanks though,