Tuesday, April 7, 2020

MySQL Subqueries

For most of my software development career, I used an Oracle database. At my current job, we use a MySQL database. So I am still learning the ins and outs of MySQL. Here is a common thing I would do in Oracle:
SELECT
  name, total_points
FROM (
  SELECT
    name,
    SUM(points) AS total_points
  FROM
    scores
  GROUP BY
    name
)
WHERE
  total_points >  10
ORDER BY
  total_points DESC, name
That would give me a list of all players who have scored more than 10 points. When I tried this same format in MySQL, I got this error:
Error Code: 1248. Every derived table must have its own alias
After a little searching, I came up with the solution. I had to name my inner query. So with a slight modification it worked:
SELECT
  tp.name, tp.total_points
FROM (
  SELECT
    name,
    SUM(points) AS total_points
  FROM
    scores
  GROUP BY
    name
) tp
WHERE
  total_points >  10
ORDER BY
  total_points DESC, name


0 comments:

Post a Comment

 
Blogger Templates