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
Related
Now I use this code:
$query = mysqli_query($conn, "(SELECT * FROM movies WHERE
MATCH(title) AGAINST('".$_SESSION['mtitle']."' WITH QUERY EXPANSION) AND
id NOT LIKE '".$_SESSION['mid']."')
UNION
(SELECT * FROM movies WHERE category LIKE '%".$cat."%' AND
id NOT LIKE '".$_SESSION['mid']."' ORDER BY RAND()) LIMIT 5");
I would like to list 5 similar movies. When there is 5 or more matches in the first part, it works good. But if isn't, the second selection isn't random, it writes always the same movies in the same sequence.
For example: If I search for Jumanji, the first suggestion is Jumanji, the second is Jumanji: Welcome to the Jungle. But the last 3 is always the same movie.
Group By think be your answer to remove any duplicate values.
`GROUP BY mtitle`
"(SELECT mtitle FROM movies WHERE
MATCH(title) AGAINST('".$_SESSION['mtitle']."' WITH QUERY EXPANSION) AND
id NOT LIKE '".$_SESSION['mid']."')
UNION
(SELECT mtitle FROM movies WHERE category LIKE '%".$cat."%' AND
id NOT LIKE '".$_SESSION['mid']."') GROUP BY mtitle ORDER BY RAND() LIMIT 5"
I have a table with some ratings for books;
These are some dummy records I have created to test this query out;
ID BookID RatersID Rating Date
1 2 3 5 (date)
2 2 4 4 (date)
SELECT `RatersID`,
COUNT(*) AS `raters`, `Rating`, COUNT(*) AS `Ratings`
FROM
`BOOKS_ratings`
GROUP BY
`BookID`
When I run the query I expected
BookID Raters Ratings
2 2 9
What I get:
RatersID raters Rating Ratings
3 2 5 2
I do not understand why this is happening?
/////////////////// Above has been answered
I have got the query working but when trying to receive the information in php the numbers are duplicated
E.g Raters = 2 PHP shows 22
Ratings = 9 PHP shows 99
$getratingq = mysqli_query($con,"SELECT `RatersID`, COUNT(*) AS `Raters`, sum(Rating) AS `Ratings` FROM `BOOKS_ratings` WHERE `BookID` ='$bookid' GROUP BY `BookID` LIMIT 1") or die("Get ratings query error");
if($getrating = mysqli_fetch_array($getratingq))
{
echo $ratings = $getrating['Ratings'];
$raters= $getrating['Raters'];
$rating = $ratings/$raters;
$stars = floor("$rating");
}
You need to use sum() to get the sum of Rating
SELECT
`BookID`,
COUNT(*) AS `raters`
sum(Rating) as Ratings
FROM
`BOOKS_ratings`
GROUP BY
`BookID`
I'm looking to see if the last 3 rows have the same userId...
I've tried count, select distinct with no luck. Any ideas?
id userId gameId switchId won
--------------------------------
1 1515 5 475 0
2 1515 5 475 0
3 1515 5 475 0
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$st = $db->prepare("SELECT COUNT(userId) AS total FROM arcadeGamesInPlay WHERE userId=:userid,gameId=:gameId AND switchId=:switchId AND won=:won ORDER by id DESC LIMIT :limit"); // need to filter for next auction
$st->bindParam(':userId', $userId);
$st->bindParam(':gameId', $gameId);
$st->bindParam(':switchId', $switchId);
$st->bindParam(':won', $won);
$st->bindParam(':limit', $limit);
$limit=3;
$won=0;
$st->execute();
$r = $st->fetch(PDO::FETCH_ASSOC);
$playedLastThreeGames= $r['total'];
You need a nested query for this. Imagine a query like this:
SELECT COUNT(DISTINCT userId) FROM arcadeGamesInPlay WHERE id IN (1, 2, 3);
This will return the number of unique userids that were found in the three rows listed - if it returns 1, then you know they're all the same.
You can combine that with a query to select the last three rows. Perhaps something like this:
SELECT id FROM arcadeGamesInPlay ORDER BY id DESC LIMIT 3
...although you may want to add a WHERE clause as well.
Altogether, your query would look like this:
SELECT COUNT(DISTINCT userId)
FROM arcadeGamesInPlay
WHERE id IN (
SELECT id
FROM arcadeGamesInPlay
ORDER BY id DESC
LIMIT 3
);
All that being said, you haven't specified what database you're actually connecting to - and if it's MySQL, you're going to run into problems, because MySQL doesn't support a LIMIT clause on a subquery with the IN operator.
An alternative form of the subquery that will work with MySQL looks like this:
SELECT COUNT(DISTINCT userId)
FROM (
SELECT userId
FROM arcadeGamesInPlay
ORDER BY id DESC
LIMIT 3
) u;
An SQL Fiddle that shows both queries can be seen here: http://sqlfiddle.com/#!2/dda29/4
I've commented out the LIMIT part of the first query so it will work in MySQL. If you change the database engine to something else (PostgreSQL for example), you should be able to uncomment that and have both queries work properly.
This is a more detailed question as my previous attempt wasn't clear enough. I'm new to MySQL and have no idea about the best way to do certain things. I'm building a voting application for images and am having trouble with some of the finer points of MySQL
My db
_votes
id
voter_id
image_id
_images
id
file_name
entrant_id
approved
_users
id
...
Basically I need to do the following:
tally up all votes that are approved
return the top 5 with the most votes
check if the user has voted on each of these 5 (return Boolean) from another table
I've tried variations of
SELECT i.id, i.file_name, i.total_votes
FROM _images i WHERE i.approved = 1
CASE WHEN (SELECT count(*) from _votes v WHERE v.image_id = i.id AND v.voter_id = ?) > 0 THEN '1' ELSE '0' END 'hasvoted'
ORDER BY i.total_votes DESC LIMIT ".($page*5).", 5
is that something I should try and do all in one query?
This query was working fine before I tried to add in the 'hasvoted' boolean:
SELECT id, file_name, total_votes FROM _images WHERE approved = 1 ORDER BY total_votes DESC LIMIT ".($page*5).", 5
At the moment I'm also storing the vote count in the _images table and I know this is wrong, but I have no idea about how to tally the votes by image_id and then order them.
Let me give this a shot to see if I understand your question:
SELECT i.*,(SELECT COUNT(*) FROM _votes WHERE i.id = image_id) AS total_votes, (SELECT count(*) from _votes where i.id = image_id and user_id = ?) as voted FROM _images AS i WHERE i.approved = 1
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