Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using outer alias in mysql subquery

I am writing a mysql query and I have a question. Can I / How do I do something like this:

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

Essentially I am trying to get data and the frequency in which that user rated that teacher. Is it possible to use an alias from one of the items I want to select in a subquery that is still in the select and not in the where clause?

like image 939
ackerchez Avatar asked Sep 24 '13 16:09

ackerchez


People also ask

Can you use alias in subquery?

When using a self-join, it is important to use a logical SQL alias for each table. (Aliases are also useful for subqueries.

Is a subquery that uses values from the outer?

In a SQL database query, a correlated subquery (also known as a synchronized subquery) is a subquery (a query nested inside another query) that uses values from the outer query. Because the subquery may be evaluated once for each row processed by the outer query, it can be slow.

Which clause is not allowed in subquery?

Subqueries cannot manipulate their results internally, that is, a subquery cannot include the order by clause, the compute clause, or the into keyword. Correlated (repeating) subqueries are not allowed in the select clause of an updatable cursor defined by declare cursor.


1 Answers

Check out 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;

or 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;

Links above show a SQL Fiddle example assuming that id is 3.

Alternatively you could have a sub query in the FROM clause:

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

Hat a look at this Fiddle.

like image 79
Trinimon Avatar answered Oct 02 '22 22:10

Trinimon