7

我正在写一个 mysql 查询,我有一个问题。我可以/我该怎么做这样的事情:

select rating, user_id, (
    -- in here I want to write a subquery to get the number of times the user_id in the outter query has rated this teacher
) as user_rated_frequency from teachers_rating where teacher_id = id

本质上,我正在尝试获取数据以及该用户评价该老师的频率。是否可以在子查询中使用我要选择的项目之一的别名,该子查询仍在选择中而不是在 where 子句中?

4

2 回答 2

20

看看这个...

SELECT rating, 
       user_id, 
       (SELECT COUNT(*) 
          FROM teachers_rating t1 
         WHERE teacher_id = 3 
           AND t1.user_id = t2.user_id) AS user_rated_frequency 
  FROM teachers_rating t2
 WHERE teacher_id = 3;

或者那个

SELECT AVG (rating) AS average_rating, 
       user_id,
       (SELECT Count(*) 
          FROM teachers_rating t1 
         WHERE teacher_id = 3 
           AND t1.user_id = t2.user_id) AS user_rated_frequency 
  FROM teachers_rating t2
 WHERE teacher_id = 3
 GROUP BY user_rated_frequency;

上面的链接显示了一个 SQL Fiddle 示例,假设id3.

或者,您可以在子句中有一个子查询FROM

SELECT AVG (t1.rating), 
       t1.user_id,
       t2.user_rated_frequency 
  FROM teachers_rating t1,
       (SELECT tr.teacher_id,
               tr.user_id,
               COUNT(*) AS user_rated_frequency 
          FROM teachers_rating tr
         GROUP BY tr.teacher_id) t2
 WHERE t1.teacher_id = t2.teacher_id
   AND t1.user_id    = t2.user_id
 GROUP BY user_id, user_rated_frequency

看看这个Fiddle的帽子。

于 2013-09-24T17:17:24.630 回答
-1

您需要将子查询(技术上称为派生表)移动到 from 子句中。像这样:

    select 
    rating, 
    user_id, 

    from teachers_rating,
    (in here I want to write a subquery to get the number of times the user_id in the outter query has rated this teacher) as user_rated_frequency f 
where teacher_id = f.id
于 2013-09-24T17:01:06.143 回答