SQL Order By id and Count star not working - php

I would like to get number of all records and get last record :
$sql_count_sms = "SELECT count(*) as total,content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = $row_num_sms['total'];
$last_my_sms = $row_num_sms['content'];
I can get number of records but I can't get last content record .
It returns first record !
Where is my wrong ?
Below codes works fine, but I think count(*) is faster than mysql_num_rows .
$sql_count_sms = "SELECT content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = mysql_num_rows($result_count_sms);
$last_my_sms = $row_num_sms['content'];
Any solution?

The grain of the two results you want is not the same. Without using a sub-query you can't combine an aggregate and a single row into the same result.
Think of the grain as the base unit of the result. The use of GROUP BY and aggregate functions can influence that "grain"... one result row per row on table, or is it grouped by user_id etc... Think of an aggregate function as a form of grouping.
You could break it out into two separate statements:
SELECT count(*) as total FROM android_users_sms WHERE user_id = :id;
SELECT * FROM android_users_sms WHERE user_id = :id ORDER BY id DESC LIMIT 1;
Also, specific to your question, you probably want a LIMIT 1 in combination with the ORDER BY to get just the last row.
Now, counter intuitively perhaps, this should also work:
SELECT count(*), content, id
FROM android_users_sms
WHERE user_id = :id
GROUP BY id, content
ORDER BY id
LIMIT 1;`
This is because we've changed the "grain" with the GROUP BY. This is the real nuance and I feel like this could probably be explained better than I am doing now.
You could also do this with a sub query like so:
SELECT aus.*,
(SELECT count(*) as total FROM android_users_sms WHERE user_id = :id) AS s1
FROM android_users_sms AS aus
WHERE user_id = :id ORDER BY id DESC LIMIT 1;

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

Get total points of user in MySQL Table with PHP

I have a MySQL table with the columns "user" and "warningpoints" for each warning as you can see in the table above. How can I get the user which has the most warningpoints in total in PHP?
You can use GROUP BY and ORDER BY and LIMIT:
SELECT t.user,sum(t.warningPoints) as sum_points
FROM YourTable t
GROUP BY t.user
ORDER BY sum_points DESC
LIMIT 1;
Or if there is only one record per person, no need to group :
SELECT t.user,t.warningPoints
FROM YourTable t
ORDER BY t.warningPoints DESC
LIMIT 1;
You can simply add below statements in your php code.
$sql = "SELECT User, Max(warningpoints) AS MaxWarningpoints FROM MyGuests GROUP BY User";
$result = $conn->query($sql);

Selecting a record where data in anouther column is at min

I need to get the record of two numbers in two columns. But I need to find where the min value is of one of the columns. And find the number that is aligned to that min number.
Right now I have the following:
$sql = "SELECT ID, MIN(price) AS minPrice FROM my_table";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["minPrice"]; // This works
echo $row["ID"]; // This is not the number that is in the record where minPrice is.
If you are looking for one row, the simplest method is order by and limit:
select t.*
from t
order by t.col2 asc
limit 1;
You need to use subqueries.
Select ID from my_table t, (select min(price) as minPrice from my_table) where t.price =minPrice;
Didn't tested it, but it should work.
It returns all the ids with the minimal price.

How can I order by count in mysql when the count need data to calculate from this select statement?

Look at my code, I want the select statement order by the count percentage after I fetch the data from this select statement, obviously, it's not logical. What can I do? Help, appreciate.
<?php
//myslq connection code, remove it because it's not relate to this question
$stm =$db->prepare("SELECT id ,term_count, COUNT(user_id) as count FROM sign WHERE term IN (:term_0,:term_1) GROUP BY user_id ORDER by count DESC");
//trying replace order by count with $combine_count, but it's wrong
$term_0="$term[0]";
$term_1="$term[1]";
$stm->bindParam(":term_0", $term_0);
$stm->bindParam(":term_1", $term_1);
stm->execute();
$rows = $stm->fetchALL(PDO::FETCH_ASSOC);
foreach ($rows as rows) {
$count=$rows['count'];
$term_count_number=$rows['term_count'];
$count_percentage=round(($count/$count_user_diff)*100);
$count_key_match=round(($count/$term_count_number)*100);
$combine_count=round(($count_percentage+$count_key_match)/2);
//issue is here, I want the select statement order by $combine_count
}
?>
SELECT id ,term_count, COUNT(user_id) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
Since "count" is a function, it would be better to put backtics around the non-function "counts", as done above.
GROUP BY should list the field not aggregated. Otherwise, it does not know which id and term_count to fetch. So, depending on what you are looking for,
Either do
SELECT user_id, COUNT(*) as `count` -- I changed this line
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
or do
SELECT id ,term_count, COUNT(*) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY id ,term_count -- I changed this line
ORDER by `count` DESC");
SQL Syntax Logic
SELECT column1, count(column1) AS amount
FROM table_name
GROUP BY column1
ORDER BY amount DESC
LIMIT 12

Deleting older database entries

I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried DELETE FROM people ORDER BY id DESC LIMIT $excess, but it just deleted the top 10 entries.
$query = "SELECT * FROM people";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count > 10) {
$excess = $count - 10;
$query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')";
mysqli_query($conn, $query);
}
You can use this:-
DELETE FROM `people`
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM `people`
ORDER BY id DESC
LIMIT 10
)
);
Also your query is logically incorrect and you are fetching the records in descending order. i.e. Latest to older and you are deleting the most recent records. Use ASC instead.
Something like this? Gets the ten latest ids in the subquery, then deletes all of the other ids.
DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10)
Your logic is all over the place, [you should ORDER BY ASC, not DESC] and your query will take ages if there are [for example] 10,000 entries because you'll have an IN clause with 9,990 entries to compare all 10,000 to.
Select the 10 most recent, and delete where NOT in.
DELETE FROM people
WHERE id NOT IN(
SELECT id
FROM people
ORDER BY id DESC
LIMIT 10
)
Maybe find the ID of the 10th element and then delete all rows which are older?

Categories