在mysql子查询中使用外部别名

时间:2013-09-24 16:57:35

标签: mysql sql database

我正在写一个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

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

2 个答案:

答案 0 :(得分:13)

查看this ...

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;

that one

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小提琴示例,假设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

答案 1 :(得分:-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