0

Basically what I have is a ratings system. 1-5 stars for 4 categories. What I'm trying to do is get a count of the results for each category. For instance:

  Category 1: 20 1 star, 32 2 star, 40 3 star, 35 4 star, 19 5 star
  ...
  Category 4: 10 1 star, 12 2 star, 45 3 star, 54 4 star, 2 5 star

I know that I can just do 20 queries, (SELECT COUNT(*) WHERE BizID=$id AND category1=1 / SELECT COUNT(*) WHERE BizID=$id AND category1=2...), but I was wondering if there was a more efficient way. Seems like if I had a large number of hits, or there were a huge number of ratings, the script would bog down pretty bad at this point. Any help would be appreciated.

Table Structure
RateID - int(10)
UserID - varchar(8)
BizID - varchar(8)
Cat1 - int(1)
Cat2 - int(1)
Cat3 - int(1)
Cat4 - int(1)
Date - int(10)
1
  • You can use IN for this. Commented Jul 11, 2014 at 6:22

2 Answers 2

1

You can get counts by Category and the Star rating in one shot using the CASE statement, as below:

SELECT
    SUM
    (
        CASE
            WHEN Cat1 = 1 THEN 1
            ELSE 0
        END
    ) Cat1_1,
    SUM
    (
        CASE
            WHEN Cat1 = 2 THEN 1
            ELSE 0
        END
    ) Cat1_2,
    SUM
    (
        CASE
            WHEN Cat1 = 3 THEN 1
            ELSE 0
        END
    ) Cat1_3,
    SUM
    (
        CASE
            WHEN Cat1 = 4 THEN 1
            ELSE 0
        END
    ) Cat1_4,
    SUM
    (
        CASE
            WHEN Cat1 = 5 THEN 1
            ELSE 0
        END
    ) Cat1_5,
    SUM
    (
        CASE
            WHEN Cat2 = 1 THEN 1
            ELSE 0
        END
    ) Cat2_1,
...
...
... 
FROM mytable
WHERE BizID=$id;
Sign up to request clarification or add additional context in comments.

Comments

0

Try with this:

<?php
$sql = "SELECT COUNT(BizID) WHERE BizID = " . $id . " AND category1 IN (1, 2, 3, 4, ...)";

2 Comments

@LinkinTED, not understood. Please write in details.
The question is not how to do it but how to do it better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.