Syntax error all expressions in a derived table must have an explicit name

Not sure what is going on here and why this is not working. I'm receiving the following error: "All expressions in a derived table must have an explicit name" - working with teradata. select ...

Not sure what is going on here and why this is not working. I’m receiving the following error:

«All expressions in a derived table must have an explicit name» — working with teradata.

    select clm.c_clm
    ,clm.c_loc
    from 
    (select *
    from pearl_p.TLTC900_CLM clm) as cl
    left join
    (select 
    max(av.d_usr_udt_lst)
    from pearl_p.TLTC913_AVY av
    group by 1) as avy
    on cl.i_sys_clm = avy.i_sys_clm

asked Sep 9, 2013 at 15:18

gfuller40's user avatar

Your max(av.d_usr_udt_lst) in your subquery doesn’t have an explicit name. You need to alias it like this:

max(av.d_usr_udt_lst) as "MaxThing"

So the query looks like

select clm.c_clm
    ,clm.c_loc
    from 
    (select *
    from pearl_p.TLTC900_CLM clm) as cl
    left join
    (select 
    max(av.d_usr_udt_lst) as "MaxThing"
    from pearl_p.TLTC913_AVY av
    group by 1) as avy
    on cl.i_sys_clm = avy.i_sys_clm

answered Sep 9, 2013 at 15:20

Derek Kromm's user avatar

Derek KrommDerek Kromm

21.2k7 gold badges52 silver badges61 bronze badges

Apart from that error, you have another error in your join:

select clm.c_clm, clm.c_loc
from (select *
      from pearl_p.TLTC900_CLM clm
     ) cl left join
     (select max(av.d_usr_udt_lst)
      from pearl_p.TLTC913_AVY av
      group by 1
     ) as avy
    on cl.i_sys_clm = avy.i_sys_clm
--------------------------^ This variable is not defined.

I think you might want something like:

select clm.c_clm, clm.c_loc
from (select *
      from pearl_p.TLTC900_CLM clm
     ) cl left join
     (select i_sys_clm, max(av.d_usr_udt_lst) as maxdate
      from pearl_p.TLTC913_AVY av
      group by i_sys_clm
     ) avy
    on cl.i_sys_clm = avy.i_sys_clm and
       cl.<date column goes here> = avy.maxdate

answered Sep 9, 2013 at 15:24

Gordon Linoff's user avatar

Gordon LinoffGordon Linoff

1.2m55 gold badges627 silver badges767 bronze badges

The Alias clm only exists within the sub-query that defines the cl alias. As such you cannot call clm outside of that sub-query. Change all the outer references to cl adn you will be fine.
While your at it, you should also gt rid of the SELECT * and explicitly identify the colums you need.

answered Sep 9, 2013 at 15:22

Declan_K's user avatar

Declan_KDeclan_K

6,6362 gold badges18 silver badges30 bronze badges

Вопрос:

Я получаю сообщение об ошибке при использовании этого запроса в MySQL.

Логика запроса верна, и я пробовал ее в Oracle, и она работает нормально, но я получаю сообщение об ошибке при работе в MySQL.

Я просмотрел предыдущие вопросы о StackOverflow, но не нашел что-то, чтобы помочь мне.

Вот запрос:

select * from
(select PM.ID, PM.Name, PM.TIMEOUT, PMS.PROCESS_MONITOR_ID, PMS.PROCESS_START_DATE
from RATOR_IMP.PROCESS_MONITOR as PM
JOIN RATOR_IMP.PROCESS_MONITOR_STATISTIC as PMS
ON PM.ID = PMS.PROCESS_MONITOR_ID
WHERE PM.ENABLED=1 and (PM.NAME='SDRRATINGENGINE11' or PM.NAME='WORKFLOWENGINE1')
order by PMS.PROCESS_START_DATE desc)
limit 10000;

И вот ошибка:

Error Code: 1248. Every derived table must have its own alias
No soultion found for query

Лучший ответ:

Вам нужно предоставить псевдоним для подзапроса, например:

select * from
(select PM.ID, PM.Name, PM.TIMEOUT, PMS.PROCESS_MONITOR_ID, PMS.PROCESS_START_DATE
 from RATOR_IMP.PROCESS_MONITOR as PM
 JOIN RATOR_IMP.PROCESS_MONITOR_STATISTIC as PMS
 ON PM.ID = PMS.PROCESS_MONITOR_ID
 WHERE PM.ENABLED=1 and (PM.NAME='SDRRATINGENGINE11' or PM.NAME='WORKFLOWENGINE1')
 order by PMS.PROCESS_START_DATE desc) as s
limit 10000;

В документации,

Подзапросы являются законными в предложении FROM SELECT. Фактический синтаксис:

SELECT… FROM (подзапрос) [AS] name…

Предложение имени [AS] является обязательным, поскольку каждая таблица в предложении FROM должна иметь имя. Любые столбцы в списке выбора подзапроса должны иметь уникальные имена.

Ответ №1

Да вам нужно указать псевдоним для полученных данных

select x.* from
(select PM.ID, PM.Name, PM.TIMEOUT, PMS.PROCESS_MONITOR_ID, PMS.PROCESS_START_DATE
from RATOR_IMP.PROCESS_MONITOR as PM
JOIN RATOR_IMP.PROCESS_MONITOR_STATISTIC as PMS
ON PM.ID = PMS.PROCESS_MONITOR_ID
WHERE PM.ENABLED=1 and (PM.NAME='SDRRATINGENGINE11' or PM.NAME='WORKFLOWENGINE1')
order by PMS.PROCESS_START_DATE desc)x <-- here
limit 10000;

In this article, we will be discussing the below points

  • HOW TO FIX THE ERROR in MySQL : Every derived table must have its own alias
  • Every derived table must have its own alias : JOIN

Let’s get started, but first, we will look into the data we will be using in our examples. Assume that we have a table sale_details with the below rows.

figure 1.1

HOW TO FIX THE ERROR in MySQL : Every derived table must have its own alias

What is a derived table?  Well, the Derived table is an expression that creates a temporary table in the FROM clause’s scope in the query. It is a subquery in the SELECT statement and FROM clause. Let’s look into an example to get the average of the maximum no_products_sold for each salesperson for a department. Observe the below query.

 SELECT 
    CEIL(AVG(max_sales))
FROM
    (SELECT 
        sale_person_name, MAX(no_products_sold) AS max_sales
    FROM
        sale_details
    GROUP BY sale_person_name);

In the above query, we created a derived table from subquery “SELECT sale_person_name, MAX(no_products_sold) AS max_sales FROM sale_details GROUP BY sale_person_name,” which is within the scope of the FROM clause.

On running the query written above to get the average of the maximum no_products_sold for each salesperson per department, we get an ERROR :

Advertisements

Action Output Message: SELECT CEIL(AVG(max_sales)) FROM (SELECT sale_person_name, MAX(no_products_sold) AS max_sales FROM sale_details GROUP BY sale_person_name) LIMIT 0, 1000 Error Code: 1248. Every derived table must have its own alias 0.00025 sec

It is highlighting that an Error:1248 Every derived table must have its alias has occurred. The reason for the same is that we need to provide an alias for the sub-queries while working in MySQL (alias is just a temporary/false name). Observe the corrected query below:

 SELECT 
    CEIL(AVG(max_sales)) AS average_of_max_sales_per_salesman
FROM
    (SELECT 
        sale_person_name, MAX(no_products_sold) AS max_sales
    FROM
        sale_details
    GROUP BY sale_person_name) AS sales_alias;   

In the above query, we have added an alias sales_alias for the derived table. On running the query now, we get the desired result.

Action Output Message: SELECT CEIL(AVG(max_sales)) FROM (SELECT sale_person_name, MAX(no_products_sold) AS max_sales FROM sale_details GROUP BY sale_person_name)as sales_alias LIMIT 0, 1000 1 row(s) returned 0.00086 sec / 0.000018 sec.

Output :-

figure 1.2

Let’s see how to work with joins while using the derived tables. We will be using the same table sale_details to get all the columns for a salesperson corresponding to the row, which shows the maximum sale for a product department wise. We need to do an inner join of the sales_details table with a derived table for the desired result. Observe the below query, it’s output, and explanation.

SELECT 
    sd1.*
FROM
    sale_details sd1
        INNER JOIN
    (SELECT 
        sale_person_name, MAX(no_products_sold) AS MaxSale
    FROM
        sale_details
    GROUP BY sale_person_name) sd2 ON sd1.sale_person_name = sd2.sale_person_name
        AND sd1.no_products_sold = sd2.MaxSale;

Action Output Message: SELECT sd1.* FROM sale_details sd1 INNER JOIN (SELECT sale_person_name, MAX(no_products_sold) AS MaxSale FROM sale_details GROUP BY sale_person_name) sd2 ON sd1.sale_person_name = sd2.sale_person_name AND sd1.no_products_sold = sd2.MaxSale LIMIT 0, 1000 4 row(s) returned 0.00097 sec / 0.000032 sec.

Output:-

figure 1.3

Explanation:- In this query, we are using an INNER JOIN with the sales_details table and the derived table.

STEP1:  The derived table created in the sub-query “SELECT sale_person_name, MAX(no_products_sold) AS MaxSale FROM sale_details GROUP BY sale_person_name” gets the sales_person_name and maximum no_products_sold grouped by sales_person_name. The alias name given to this derived table is sd2.

STEP2: Select all the details from the sales_details table in the outer-query alias name is sd1.

STEP3: Finally, doing an INNER JOIN on the derived table and sales_details table ON sale_person_name AND ON no_products_sold from sales_details table, MAX(no_products_sold) from the derived table.

We hope this article provided a good understanding of the alias while using the derived tables. Good Luck !!!

Advertisements

Thanks for reading.

Are you writing a query in MySQL and getting an error of “1248: Every derived table must have its own alias”? If so, it’s a simple error to fix.

So you’ve got this error in MySQL. How do you fix it?

The short answer is you need to give your subqueries an alias in your SELECT statement. Add an alias after the closing bracket of the FROM clause subquery.

In other SQL vendors, this is not required, but MySQL requires you to alias your subqueries.

What does this mean?

Let’s take a look at an example.

Example of a Derived Table

A derived table is a SELECT subquery within the FROM clause of your main query. It’s treated like a table because it has columns and returns rows. It can be used in place of a table in the FROM clause, for example. It’s often called an inline view or just a subquery.

Here’s an example of a derived table:

SELECT customer_city,
COUNT(*) AS order_count,
SUM(order_amount) AS order_sum
FROM (
  SELECT o.order_id,
  o.customer_city,
  o.order_amount
  FROM orders o
  INNER JOIN customer c ON o.customer_id = c.customer_id
)
GROUP BY customer_city;

This query finds the city, number of orders, and the sum of the order amounts from the orders and customer tables.

Let’s break this query down.

The query has an outer query and an inner query. The inner query is used to get data from orders and customers:

SELECT o.order_id, o.customer_city, o.order_amount
FROM orders o
INNER JOIN customer c ON o.customer_id = c.customer_id

This gets data from two tables, joining on a common field. This is the “derived table”.

The outer query selects a few columns from this subquery. Rather than using a table, the data comes from the results of this subquery.

SELECT customer_city,
COUNT(*) AS order_count,
SUM(order_amount) AS order_sum
FROM (
...
)
GROUP BY customer_city;

It shows the customer_city, two aggregate functions, and groups by the city.

This is the entire query again:

SELECT customer_city,
COUNT(*) AS order_count,
SUM(order_amount) AS order_sum
FROM (
  SELECT o.order_id,
  o.customer_city,
  o.order_amount
  FROM orders o
  INNER JOIN customer c ON o.customer_id = c.customer_id
)
GROUP BY customer_city;

What happens if you run this query in MySQL?

You’ll get this error:

Error 1248: Every derived table must have its own alias

How do you resolve this?

Solution to “Every derived table must have its own alias”

The reason you get this error is that in MySQL, every derived table (subquery that is a SELECT query) needs to have an alias after it.

The query example here did not have an alias for the subquery. The alias for a subquery is the same as a column alias. It goes after the closing brackets for the FROM clause for the subquery.

So, in this example, all we need to do to resolve this error is to add an alias after the closing bracket.

The alias can be almost anything you like: a single letter, a word, a few letters. I often use the word “sub” if it’s a small query (for subquery), or something more descriptive if it’s a longer query.

SELECT customer_city,
COUNT(*) AS order_count,
SUM(order_amount) AS order_sum
FROM (
  SELECT o.order_id,
  o.customer_city,
  o.order_amount
  FROM orders o
  INNER JOIN customer c ON o.customer_id = c.customer_id
) sub
GROUP BY customer_city;

Notice how the word “sub” is added after the closing bracket on the second last line? That’s the alias for the subquery or derived table. This alias is required in MySQL but not other vendors.

Running this query should work and you should not get the “Every derived table must have its own alias” error anymore.

Optional: Add the AS Keyword

You could add the AS keyword, as this is an optional part of adding an alias, but it’s up to you. This will also work:

SELECT customer_city,
COUNT(*) AS order_count,
SUM(order_amount) AS order_sum
FROM (
  SELECT o.order_id,
  o.customer_city,
  o.order_amount
  FROM orders o
  INNER JOIN customer c ON o.customer_id = c.customer_id
) AS sub
GROUP BY customer_city;

So, that’s how you can resolve this derived table alias error. Add an alias to your subquery.

Понравилась статья? Поделить с друзьями:
  • Pycharm как изменить папку проекта
  • Synology ошибка вентилятора
  • Pycharm как изменить дизайн
  • T6sp exe call of duty black ops 2 ошибка при запуске
  • Swift kf4 истекло время для как исправить