I have a database that looks something like this:
user_id photo_id
1 1
1 2
1 3
1 4
2 5
2 6
I want to get a list of the most popular users from it. Like this:
Popular Users: 1 (4) & 2 (2)
How would I go about doing that in mysql in PHP?
Thanks, Coulton
PS: I do know much about mysql commands so you don't have to dumb it down. Thanks!
The basic query would be:
select user_id, count(user_id) as cnt
from yourtable
group by user_id
order by cnt desc
To display the results, something like:
$results = array()
while($row = mysql_fetch_assoc($query_result)) {
$results[] = "{$row['user_id']} ({$row['cnt']})"
// repeat for however many results you want
}
echo "Popular user: ", implode(" & ", $results);
select user_id, count(user_id) as count from table order by count desc group by user_id
something like that anyway...
This can be accomplished using only SQL commands. Here's what I'd do:
SELECT user_id, count(user_id) uid_count
FROM <<table>>
GROUP BY user_id
ORDER BY uid_count DESC
LIMIT 5;
GROUP BY collects rows that all have the same user_id, and ORDER BY ... DESC sorts the results in descending order, so the first rows represent the most popular users. LIMIT gives you the top 5 results.
The database query will look something like this:
select user_id, count(photo_id) as c
from table group by user_id
order by c desc limit 5;
In PHP, it would look something like this:
$sql = 'select user_id, count(photo_id) as c from table group by user_id order by c desc limit 5';
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['user_id'];
echo $row['c'];
}
SELECT COUNT(a.category_id) as cnt,b.category,b.image FROM bookings as a
INNER JOIN service_category as b ON a.category_id=b.category_id
GROUP BY a.category_id ORDER BY cnt DESC LIMIT 6
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 have 3 tables, users, warnings, warningnames.
The content of the tables is as follows:
Users(simplified):
u_id, username, password, rank
Warnings:
w_id, wn_id, u_reporter_id, u_reported_id
Warningnames:
wn_id, warningInfo, warningPoints
I have a loop in PHP which gets me all users with a simple query:
SELECT *
FROM users
WHERE u_id < :startcount
ORDER BY u_id DESC
LIMIT :perpage
How do I make a query which gets all users but puts the users with the most warnings at the top and the users with rank 0 at the bottom?
The query I have so far is:
SELECT users.*, COUNT(warnings.w_id) as warningCount
FROM users
LEFT JOIN warnings
ON users.u_id = u_reported_id
WHERE u_id < :startcount
ORDER BY warningCount DESC
LIMIT :perpage
But that doesn't return what I want, it just returns the warningCount of all users in a single query that fit the WHERE statement.
Example fiddle:
http://sqlfiddle.com/#!9/ec6c2d/6
Sample PHP code:
<?php
$query = $this->handler->prepare('SELECT * FROM users WHERE u_id < :startcount ORDER BY u_id DESC LIMIT :perpage');
try{
$query->execute([
':startcount' => 25,
':perpage' => 25
]);
}
catch(PDOException $e){
echo $e->getMessage();
}
while($fetch = $query->fetch(PDO::FETCH_ASSOC)){
echo $fetch['username'] . '<br />';
}
?>
How can I correct this and order by a warningCount column but put all users with rank 0 at the end?
If I understand it, you want to order by warning count, but ignore users with rank = 0 on that query ??
if that's the case, what you need is group by, and then order by using case when,
here's what I came up :
SELECT users.*, COUNT(warnings.w_id) as warningCount
FROM users
LEFT JOIN warnings
ON users.u_id = u_reported_id
WHERE u_id < 10
group by users.u_id
ORDER BY
case when rank = 0
then 0
else COUNT(warnings.w_id) + 1
end
DESC
LIMIT 25
I add +1 on order by to make sure, users with rank 0 is always at the bottom.
Edit :
I Add the where startCount and the limit to the query
The SQL Fiddle was helpful in explaining you situation, and I think you're looking for GROUP BY. Also note that you can order by multiple fields.
I've edited your fiddle slightly: https://www.db-fiddle.com/f/av9d6ordS9XVpavwzZUs8W/0
SELECT u.*, COUNT(w.wn_id) warnings
FROM users u
INNER JOIN warnings w ON u.u_id = w.u_reported_id
GROUP BY u.u_id
ORDER BY warnings DESC, u.rank DESC
# LIMIT 10
Is possible, and how to ask MySQL for
SELECT * FROM my_table ORDER by row_id DESC LIMIT 8
get the last 8, newest record from my table, with randomized order for PHP showing method
$results = $mysqli->query($query);
while($row = $results->fetch_assoc()) {
echo $row['my_col_name'];
}
Colud I, and where put the rand() in my SQL query?
Without randomize I get last 8 rows ORDERED 10,9,8,7,6,5,4,3
I want to get in the following order:
9,7,5,4,6,10,3,8;
8,7,3,6,10,9,5,4
...
You can place it inside another select:
SELECT * FROM (SELECT * FROM my_table ORDER by row_id DESC LIMIT 8) t ORDER BY RAND()
Use a subquery:
SELECT t.*
FROM (SELECT t.*
FROM my_table t
ORDER by row_id DESC
LIMIT 8
) t
ORDER BY rand();
I have this code for counting number of replies in one topic,
$sql = mysql_query("SELECT count(*) FROM ".prefix."REPLY WHERE TOPIC_ID = '$t' AND R_AUTHOR = '$m' ".$Open_SQL." ") or die(mysql_error());
$Count = mysql_result($sql, 0, "count(*)");
if ($Count > 0) {
$Count = $Count;
}
else {
$Count = "";
}
return($Count);
mysql_free_result($sql);
}
it shows the results fine, what I need is to order this results in DESC.
any suggestions?
You are just selecting Count(*) which means there is nothing to sort, because you will exactly get ONE dataRow, containing the count.
What you probably want to do is to add a GROUP BY-clause and select different Stuff and order it by count:
table
user | type
1 apple
2 apple
3 cherry
With such a table, you can group by type and sort the cherry/apple count later.
SELECT count(*) AS c, type FROM table GROUP BY type ORDER by c DESC/ASC
Result:
c | type
2 apple
1 cherry
But without GROUP BY it would just return the total count: 3 - no sorting possible of course.
you probably want to do something like this
SELECT some-field, count(*) as count
FROM your-table
WHERE your-clauses
AND more-clauses
GROUP BY some-field
ORDER BY some-field desc
i have made a query to find how many people have voted for an entry and it goes like this:
$query = "SELECT itemid, COUNT(*) totalcount
FROM jos_sobi2_plugin_reviews
GROUP BY itemid
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
";
The sql works and produces the following table.
entry id totalcount
-------- ----------
202 5
203 20
204 15
...
I only want to display the column totalcount and i dont succeed.
maybe someone knows which query should i right on my php?
thanks, ronen!
$query = "SELECT COUNT(1) totalcount
FROM jos_sobi2_plugin_reviews
GROUP BY itemid
HAVING COUNT(1) > 1
ORDER BY COUNT(1) DESC
";
This could work fine