加入2个表格进行查看

时间:2015-12-26 08:38:43

标签: mysql sql select join group-by

我有两张食谱表和recipe_ratings
我不知道如何从recipe_rating获得AVG(rating_value) 并加入他们

食谱表(获取'*')并加入AVG(recipe_value)
按date_posted排序

3 个答案:

答案 0 :(得分:0)

执行以下查询:

SELECT t1.*, t2.avg(rating) as 'Average Rating' FROM table1 t1 INNER JOIN table2 t2 
ON t1.id = t2.id GROUP BY t1.id

答案 1 :(得分:0)

试试这个:

public class Numbers {
    static Scanner numberScanner = new Scanner(System.in);
    public static int answer;

    public static int insertNumbers(int num1, int num2) {
        System.out.println("Insert two numbers");
        num1 = numberScanner.nextInt();
        if (numberScanner.hasNext()) {
            num2 = numberScanner.nextInt();
        } else {
            System.out.println("Equation format incorrect");
            //stop method and start over again from "Insert two numbers".
        }
        answer = num1 + num2;
        return answer;
    }
}

答案 2 :(得分:0)

这是我的方法:

表&数据:

CREATE TABLE recipes 
    (`id` int, `recipe_name` varchar(7))
;
CREATE TABLE recipe_ratings 
    (`id` int, `recipeId` int,`rating_value` int,`date_posted` datetime)
;

INSERT INTO recipes
    (`id`, `recipe_name`)
VALUES
    (1, 'Cake'),
    (2, 'Bun'),
    (3, 'Hot Dog'),
    (4, 'Tea')
;

INSERT INTO recipe_ratings
  (`id`, `recipeId`,`rating_value`,`date_posted`)
VALUES
    (1,1,3,'2015-03-20 10:30:00.000'),
    (2,2,4,'2015-06-20 10:30:00.000'),
    (3,3,5,'2014-03-20 10:30:00.000')
;

<强>查询:

SELECT R.*, AVG(RR.rating_value) rating_value
FROM recipes R
LEFT JOIN recipe_ratings RR ON R.id = RR.recipeId 
GROUP BY RR.date_posted,R.id 
ORDER BY RR.date_posted DESC

SqlFiddle Demo