Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Every derived table must have its own alias - error from combination descending MySQL

Tags:

mysql

union

I want to order one mysql table by two strtotime timestamps from two different columns. I've got the following mysql command:

SELECT * FROM (
(SELECT '1' AS `table`,  `vid_req_timestamp` AS `timestamp`, `title` FROM `movies` WHERE `vid_req` = '1')
UNION
(SELECT '2' AS `table`,  `ost_req_timestamp` AS `timestamp`, `title` FROM `movies` WHERE `ost_req` = '1')
)
ORDER BY `timestamp` DESC

This gives me an error:

#1248 - Every derived table must have its own alias

I want to combine vid_req_timestamp and ost_req_timestamp and make those descending. And it's important to know where the timestamp came from (somehow).

like image 427
Paul Gerarts Avatar asked Feb 02 '12 20:02

Paul Gerarts


People also ask

How do you solve the error Every derived table must have its own alias?

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.

Could not run Statement Every derived table must have its own alias?

This error is caused by the fact that you basically generate a new table with your subquery for the FROM command. That's what a derived table is, and as such, it needs to have an alias (actually a name reference to it).

What must a derived table have so that you can reference it later in the query?

Unlike a subquery, a derived table must have an alias so that you can reference its name later in the query.

What is error 1248 in mySQL?

mySQL error: #1248 - Every derived table must have its own alias.


1 Answers

In this case, the derived table that requires an alias is the one that you are SELECTing * from.

Indentation helps make that clearer.

SELECT * FROM 
(
    (SELECT '1' AS `table`,  `vid_req_timestamp` AS `timestamp`, `title` FROM `movies` WHERE `vid_req` = '1')
    UNION
    (SELECT '2' AS `table`,  `ost_req_timestamp` AS `timestamp`, `title` FROM `movies` WHERE `ost_req` = '1')
) AS `some_table_name_lol_this_is_an_alias`
ORDER BY `timestamp` DESC
like image 193
TehShrike Avatar answered Sep 21 '22 02:09

TehShrike