I have a simple table in phpmyadmin called name with only 1 column id which is look like this
id
--------
a
b
a
a
a
a
b
Now i want to show most used id on my PHP page.
Here is my code:
$sql_a = mysql_query(SELECT id FROM name WHERE id='a');
$count_a = mysql_num_rows($sql_a);
$sql_b = mysql_query(SELECT id FROM name WHERE id='b');
$count_b = mysql_num_rows($sql_b);
if($count_a > $count_b)
{
$most_used_id = "A";
}
else
{
$most_used_id = "B";
}
echo "<h1>MOST USED ID IS $most_used_id</h1>";
Currently I have only 2 types of id but in future I will have multiples (maybe 300+) id's, so is there a way to make query dynamic and get only most used value
That's very redundant code. You'd be better off with
SELECT id, count(id) AS cnt
FROM name
ORDER BY cnt DESC
GROUP BY id
LIMIT 1
that'll give you the "most popular" id value, and just how popular it is. If you need to get the count of all the ids, then remove the limit line.
Try the following query:
select id, count(id) cnt
from name
group by id
order by cnt desc
limit 1
Related
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
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;
Well, i found this simple script online somewhere for selecting the next row and selecting the previous row.
This works. (Next page)
$currentid = $_GET['id'];
$nextquery= mysqli_query($conDB,"SELECT * FROM vids WHERE ID > $currentid ORDER BY ID ASC LIMIT 1")or die (mysqli_error($conDB));
However, this dosent, it returns the current page id instead of the previous id.
What i want is that it gets the last available id that is on the database.
$prevquery= mysqli_query($conDB,"SELECT * FROM vids WHERE ID < $currentid ORDER BY ID desc LIMIT 1")or die (mysqli_error($conDB));
Please someone help me, i would greatly appreciate it! :D
Best regards Dániel
To find the largest value of the field "ID" from the "vids" table, you will want to use the following query:
SELECT ID FROM vids ORDER BY ID DESC LIMIT 1
To find the previous and next rows in the table, the queries you are using look correct, however there appears to be a typo in the first line calculating the $currentid:
$currrentid = $_GET=['id'];
This line should be:
$currrentid = $_GET['id'];
remove DESC for the previous query
"What i want is that it gets the last available id that is on the database."
`SELECT MAX(ID) FROM table_name;`
will give you the last record id in a table.
Next:
select * from table_name where ID = (select min(ID) from table_name where ID > $_GET['id'])
Previous:
select * from table_name where ID = (select max(ID) from table_name where ID < $_GET['id'])
Or you can optimise the query and have it all completed in one call:
select * from table_name where (
ID = IFNULL((select min(ID) from table_name where ID > $_GET['id']),0)
or ID = IFNULL((select max(ID) from table_name where ID < $_GET['id']),0)
)
I have a function that is supposed to search the db for the highest 'score'.
The Db is structured like this:
----------------------------------------
| id | UrlId | Article | Score |
----------------------------------------
I can get the highest score correctly, but I do not know how to return the full object based on the highest score.
I am reluctant to loop through the entire table and test the values of 'score' to see which is the highest (although as I type that I suspect I am doing it anyway) because the db will potentially have 10000's of records.
I am sure that this is dead simple, but I have "the dumb and I cant brain today" Does anyone know a more elegant solution?
My end result would have to be something like this:
if there are 4 UrlId;s with the same top score, the user would need to see:
UrlId example1 20(score)
UrlId example2 20(score)
UrlId example3 20(score)
UrlId example4 20(score)
all other results would not be displayed.
function gethappiestBlog() {
$happiestBlogs = /* This is the data that I loop through, this is correct */
$happinessArray = array();
foreach($happiestBlogs as $happiestBlog) {
$happinessArray[]= $happiestBlog->Score;
}
$maxHappy = max($happinessArray);
echo $maxHappy;
}
SELECT fieldlist
FROM `tableName`
WHERE `score` = (SELECT MAX(`score`) FROM `tableName`)
Couldn't you use a query?
SELECT *
FROM table_name
ORDER BY score
DESC LIMIT 1;
If you need multiple scores, you could then use a subquery:
SELECT *
FROM table_name
WHERE score =
(SELECT score
FROM table_name
ORDER BY score
DESC LIMIT 1;
);
Try this.
$dbh=new PDO(DSN,USERNAME,PASSWORD);
$stmt=$dbh->prepare("SELECT * FROM TABLE_NAME ORDER BY Score DESC");
$stmt->execute();
while($happiestBlog=$stmt->fetch(PDO::FETCH_OBJ)):
echo $happiestBlog->Score;
endwhile;
Here ORDER BY Score DESC fetch the the row first ehich has highest Score.
is it possible to order a select from mysql by using a known id first.
Example:
$sql = "SELECT id, name, date FROM TABLE ORDER BY "id(10)", id DESC
Not sure if the above makes sense but what I would like to do is first start ordering by the known id which is 10 which I placed in quotes "id(10)". I know that cannot work as is in the query but it's just to point out what I am trying to do.
If something similar can work I would appreciate it. Thanks.
SELECT id, name, date
FROM tbl
ORDER BY CASE WHEN id = 10 THEN 0 ELSE 1 END, id DESC
How about this?
SELECT id, name, date, IF(id = 10, 1, 0) AS sort_field
FROM TABLE
ORDER by sort_field, id DESC