Combine two SQL statements with arithmetic (not joining per se) - mysql

I have a plugin that counts helpful votes for reviews on my site ('helpful', 'funny', 'cool', and it gives the option of adding other descriptors as well. So I've added 'not helpful'.
Now I'm trying to customize the query used to display the reviews with the most votes by taking 'not helpful' votes into account (subtracting them from the helpful votes) instead of just counting a total of all votes.
So originally the query used for this was:
SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` GROUP BY review_id ORDER BY count DESC LIMIT 5
And I've found that I can count the helpful votes (where the number in the 'rate' column is 0, 1, or 2), like so:
SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5
And I can count the non-helpful votes (where the number in the 'rate' column is 3), like so:
SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5
But what I can't figure out is how to combine these two select statements such that the top 5 'count' results show a difference of the counts from each query.
I don't want a union because no subtraction is done, and I've tried various permutations of multiple selects, but can't manage to work this out.
Any suggestions?
An example table: Example Table
In the example above, if all votes are counted blindly, review #4 is ranked higher than review #10, but if not-helpful votes are taken into account, #10 is ranked higher with a net total of 1 versus review #4's net total of 0.
Make sense?

try this:
select a.review_id,b.review_id,a.count,b.count from
(SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5) as a
left join
(SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5) as b
on a.review_id = b.review_id
this is work if review_id of first query = review_id of second query otherwise you can use also <> to both.
other option use union all
SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` <3 GROUP BY review_id ORDER BY count DESC LIMIT 5
union all
SELECT review_id, COUNT(*) AS count FROM `wp_reviews_ratings` where `rate` >2 GROUP BY review_id ORDER BY count DESC LIMIT 5

Related

how can I get a DISTINCT from mySQL but only for 1 field?

I have a row with products and I'd like to get 10 random records, but a maximum of 1 row per user_id. Right now I have this:
SELECT user_id, product_id, price, name, category, is_featured
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1
ORDER BY RAND() DESC LIMIT 0,12
I tried doing a SELECT DISTINCT user_id, ... but that doesn't work. The table has 100's of products and each user_id may have multiple ones, but I'd like to retrieve a maximum of 1 per user_id, but still a total of 10.
Is that possible at all without a more complex structure?
I may be missing something, but have you tried doing a GROUP BY?
SELECT user_id, product_id, price, name, category, is_featured
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1
GROUP BY user_id -- SPECIFY FIELD HERE
ORDER BY RAND() DESC
LIMIT 0,12
This will group one row per user, or whichever field you desire to group by.
Try something like that with grouping in main query after random ordering in subquery:
SELECT * FROM
(SELECT user_id, product_id, price, name, category, is_featured
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1
ORDER BY RAND()) AS subquery
GROUP BY user_id
LIMIT 0,10

Select sum of top three scores for each user

I am having trouble writing a query for the following problem. I have tried some existing queries but cannot get the results I need.
I have a results table like this:
userid score timestamp
1 50 5000
1 100 5000
1 400 5000
1 500 5000
2 100 5000
3 1000 4000
The expected output of the query is like this:
userid score
3 1000
1 1000
2 100
I want to select a top list where I have n best scores summed for each user and if there is a draw the user with the lowest timestamp is highest. I really tried to look at all old posts but could not find one that helped me.
Here is what I have tried:
SELECT sum(score) FROM (
SELECT score
FROM results
WHERE userid=1 ORDER BY score DESC LIMIT 3
) as subquery
This gives me the results for one user, but I would like to have one query that fetches all in order.
This is a pretty typical greatest-n-per-group problem. When I see those, I usually use a correlated subquery like this:
SELECT *
FROM myTable m
WHERE(
SELECT COUNT(*)
FROM myTable mT
WHERE mT.userId = m.userId AND mT.score >= m.score) <= 3;
This is not the whole solution, as it only gives you the top three scores for each user in its own row. To get the total, you can use SUM() wrapped around that subquery like this:
SELECT userId, SUM(score) AS totalScore
FROM(
SELECT userId, score
FROM myTable m
WHERE(
SELECT COUNT(*)
FROM myTable mT
WHERE mT.userId = m.userId AND mT.score >= m.score) <= 3) tmp
GROUP BY userId;
Here is an SQL Fiddle example.
EDIT
Regarding the ordering (which I forgot the first time through), you can just order by totalScore in descending order, and then by MIN(timestamp) in ascending order so that users with the lowest timestamp appears first in the list. Here is the updated query:
SELECT userId, SUM(score) AS totalScore
FROM(
SELECT userId, score, timeCol
FROM myTable m
WHERE(
SELECT COUNT(*)
FROM myTable mT
WHERE mT.userId = m.userId AND mT.score >= m.score) <= 3) tmp
GROUP BY userId
ORDER BY totalScore DESC, MIN(timeCol) ASC;
and here is an updated Fiddle link.
EDIT 2
As JPW pointed out in the comments, this query will not work if the user has the same score for multiple questions. To settle this, you can add an additional condition inside the subquery to order the users three rows by timestamp as well, like this:
SELECT userId, SUM(score) AS totalScore
FROM(
SELECT userId, score, timeCol
FROM myTable m
WHERE(
SELECT COUNT(*)
FROM myTable mT
WHERE mT.userId = m.userId AND mT.score >= m.score
AND mT.timeCol <= m.timeCol) <= 3) tmp
GROUP BY userId
ORDER BY totalScore DESC, MIN(timeCol) ASC;
I am still working on a solution to find out how to handle the scenario where the userid, score, and timestamp are all the same. In that case, you will have to find another tiebreaker. Perhaps you have a primary key column, and you can choose to take a higher/lower primary key?
Query for selecting top three scores from table.
SELECT score FROM result
GROUP BY id
ORDER BY score DESC
LIMIT 3;
Can you please try this?
SELECT score FROM result GROUP BY id ORDER BY score DESC, timestamp ASC LIMIT 3;
if 2 users have same score then it will set order depends on time.
You can use a subquery
SELECT r.userid,
( SELECT sum(r2.score)
FROM results r2
WHERE r2.userid = r.userid
ORDER BY score DESC
LIMIT 3
) as sub
FROM result r
GROUP BY r.userid
ORDER BY sub desc
You should do it like this
SELECT SUM(score) as total, min(timestamp) as first, userid FROM scores
GROUP BY userid
ORDER BY total DESC, first ASC
This is way more efficient than sub queries. If you want to extract more fields than userid, then you need to add them to the group by.
This will of cause not limit the number of scores pr user, which indeed seems to require a subquery to solve.

SQL statement Max(Count(*))

Basically I have a review table for product. The attributes are reviewID, reviewCustName, reviewText, productID. So I wonder is there any ways to count the product with most reviews? Here is my SQL statement:
SELECT productID, count(*) AS mostReviews, MAX(mostReviews) FROM sm_review GROUP BY productID;
I wonder is it possible to write such SQL statement? Or i there any better way?
Thanks in advance.
You can use the following to get the result. This gets the total count for each product but when you order the count in a descending order and apply LIMIT 1 it returns only the product with the most reviews:
select count(*) total
from sm_review
group by productId
order by total desc
limit 1
It should just be;
SELECT count(*) AS num_reviews FROM sm_review
GROUP BY productID ORDER BY num_reviews DESC LIMIT 1;
Note the ORDER BY num_reviews and the LIMIT 1 which limits the number of results.

MySql order by COUNT and list the total count

I am using this code to count and sort from my database:
$qry = "select entertainer, count(*) from final_results group by entertainer order by count(*) desc";
I get the right result, in as much as it lists all the contents in order or popularity.
What I would like is the top 5 results to display, with a count for each of them and then a total count of all the results.
e.g.
Top response (10)
Second response (8)
Third response (6)
etc...
Total count = 56
I would appreciate any help and advice.
Thanks,
John C
You can get the totaly using WITH ROLLUP, but that won't work well with the LIMIT 5 you want in order to only fetch the top five results. (Edit:) It will also not work with the ordering, as discussed in the comments.
So you'll either have to fetch all results, not just the top 5, and sort them in the application, or use two distinct queries, possibly merged on the server side using UNION the way #RedFilter suggests. But if you do two separate queries, the I personally would rather issue each one separately from the client application, as splitting the total from the top five later on is too much work for little gain.
To fetch all results, you'd use
select entertainer, count(*)
from final_results
group by entertainer with rollup
To do two distinct fetches you'd use
select entertainer, count(*)
from final_results
group by entertainer
order by count(*) desc
limit 5
and
select count(*)
from final_results
If you want both in a single union, you can do this as
(select 1 as unionPart, entertainer, count(*) as count
from final_results
group by entertainer
order by count(*) desc
limit 5)
union all
(select 2 as unionPart, 'Total count', count(*) as count
from final_results)
order by unionPart asc, count desc
select entertainer, count
from (
(select entertainer, count(*) as count, 1 as sort
from final_results
group by entertainer
order by count(*) desc
limit 5)
union all
(select 'Total count', (select count(*) from final_results), 2 as sort)
) a
order by sort, count desc

Find avg of rating for each item

I have a table with feilds : file_id, rating, user_id
There is one rating per user_id, so there could be many rating (in scale of 0-5) for a single file_id.
I want to find avg of ratings for every file_id and then display 5 file_id with highest avg rating.
Actually my sql query looks like:
SELECT m.server_domain, m.original_name, m.type, m.title, m.views,
m.description, m.hash, AVG(mr.rating_scale5) as avg_rating_scale5
FROM c7_media m, c7_storage s, c7_media_ratings mr
WHERE s.public=1 AND m.storage_hash = s.hash AND m.hash = mr.media_hash
GROUP BY mr.media_hash
How should I do this?
Zeeshan
Group by a file_id and then simply order by the average. Cut off all records that fall below the top 5.
SELECT
file_id, AVG(rating) as avg_rating
FROM
table
GROUP BY
file_id
ORDER BY
avg_rating DESC
LIMIT 5
SELECT `file_id`, AVG(`rating`) as a FROM `table`
GROUP BY `file_id` ORDER BY a DESC LIMIT 5
Replace 'table' with the name of your table.