Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL UNION - Every derived table must have its own alias

I am looking for a solution:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` from (
(SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_07` WHERE `k_id` = '123') 
UNION ALL 
(SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_08` WHERE `k_id ` = '123') 
) group by id, month

MySQL: Every derived table must have its own alias

like image 210
user3270967 Avatar asked Aug 16 '14 14:08

user3270967


People also ask

Why Every derived table must have its own alias?

Unlike a subquery, a derived table must have an alias so that you can reference its name later in the query. If a derived table does not have an alias, MySQL will issue the following error: Every derived table must have its own alias.

What is Union all in MySQL?

MySQL UNION ALL operator is a union query command which syndicates multiple SELECT statements' results into a single result row. Like, MySQL UNION operator it is also a useful command in MySQL database to combine more than two of the output set provided by the use of SELECT queries.

What is error 1248 in MySQL?

mySQL error: #1248 - Every derived table must have its own alias. 0. Unable to perform union, getting #1248 - Every derived table must have its own alias error.

What is a derived table?

A derived table is an expression that generates a table within the scope of a query FROM clause. For example, a subquery in a SELECT statement FROM clause is a derived table: SELECT ... FROM (subquery) [AS] tbl_name ...


2 Answers

Exactly what the error message says. In your (simplified) query:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` 
from (
  ... inner select 
) 
group by id, month;

You didn't specify an alias for the derived table. So it should be:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` 
from (
  ... inner select 
) as t -- this is the change
group by id, month;

Btw: the parentheses around the select parts of a union are totally useless. I suggest removing them for clarity:

SELECT SUM(`quant`), MONTH(`date`) AS month, `id` 
from (
  SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_07` WHERE `k_id` = '123'
  UNION ALL 
  SELECT `date`, `id`, count(`hit`) AS `quant ` FROM `stat_2014_08` WHERE `k_id ` = '123'
) as t -- this is the change
group by id, month;
like image 102
a_horse_with_no_name Avatar answered Sep 21 '22 12:09

a_horse_with_no_name


You need to give aliases to your queries:

SELECT   SUM(`quant`), MONTH(`date`) AS month, `id` 
FROM     ((SELECT `date`, `id`, count(`hit`) AS `quant` 
           FROM   `stat_2014_07` 
           WHERE  `k_id` = '123') t1
          UNION ALL 
          (SELECT `date`, `id`, count(`hit`) AS `quant` 
           FROM   `stat_2014_08` 
           WHERE  `k_id ` = '123') t2
         ) t_union
GROUP BY id, month
like image 24
Mureinik Avatar answered Sep 21 '22 12:09

Mureinik