سؤال

For every bd_comments.commentid ( meaning unique comment ) I need to join an average of all the ratings other users have supplied to the end of the row of each comment.

The table commentrate holds all the rates each user makes and the common key is the comment_id. In comment rate the field is called comment_id and in bd_comments it is just called commentid.

I can make sql select the average and join it to a single row but I cannot make it do this for all the rows. The example below only returns one result where the comment_id is specified.

select commentrate.comment_id, floor(avg(commentrate.rating)), 
bd_comments.comment, bd_comments.author_id from commentrate, bd_comments 
WHERE commentrate.comment_id= 1

This statement selects average of all the ratings for a specific commentid and return the average attached to the other fields I need, but only returns one row. There are several unique commentid's. I need a table that has a comments average rating on the end of the comment's row to make a top rated page.

هل كانت مفيدة؟

المحلول

Your schema(I guessed because you failed to provide one)

CREATE TABLE bd_comments 
    (
     commentid int , 
     comment varchar(10),
     author_id int
    );

CREATE TABLE commentrate 
    (
     comment_id int , 
     rating int,
     author_id int
    );

INSERT INTO bd_comments
VALUES
(1, "comment 1", 100),
(2, "comment 2", 200),
(3, "comment 3", 300);

INSERT INTO commentrate
VALUES
(1, 3.5, 100),
(2, 4, 100),
(3, 5, 100),
(1, 2.5, 200),
(2, 1, 200);

Here is the query

SELECT cr.comment_id, floor(avg(cr.rating)) rating,c.comment, c.author_id
FROM commentrate cr, bd_comments c
WHERE cr.comment_id = c.commentid
GROUP BY cr.comment_id

Output

| COMMENT_ID | RATING |   COMMENT | AUTHOR_ID |
|------------|--------|-----------|-----------|
|          1 |      3 | comment 1 |       100 |
|          2 |      2 | comment 2 |       200 |
|          3 |      5 | comment 3 |       300 |

demo

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top