简体   繁体   中英

Select with UNION ALL and ORDER BY

I've trying to query from a few tables with UNION ALL but I get this error on the ORDER clause:

#1054 - Unknown column 'Time' in 'order clause'

I have column Time in the table. This is the query:

SELECT * from
(SELECT table, 'as'  from as
   UNION ALL
 SELECT table, 'as'  from as1
   UNION ALL
 SELECT table, 'as'  from as2
   UNION ALL
 SELECT table, 'as'  from as3) asAllWrong
 WHERE table not like 'as%' OR length(table) < 12
 ORDER BY Time='2015-06-02 9:00:00;

So, how exactly I can query this to show me all wrong entry from those tables and this table? And why did I get this error even if there is a column called Time ?

Edit: My mistake they are different tables as, as1, as2... And I want to query all wrong entries in that time as I said.

EDIT: This is what is look like now and is working good so far. Note that this is for me.. will not go in any production and will be used sometimes so I don't really need performance .. etc..

SELECT * from
( SELECT as.*, 'as'  from as
   UNION ALL
 SELECT as1.*, 'as1'  from as1
   UNION ALL
 SELECT as2.*, 'as2'  from as2
   UNION ALL
 SELECT as3.*, 'as3'  from as3) asAllWrong
 WHERE as not like 'as%' OR length(as) < 12
 ORDER BY Time='2015-06-02 9:00:00' ASC;

While the query looks very confusing, the bottom line is that your result in-memory table created via UNION ALL doesn't contain the field Time and that's why you have an error.

As for why it's not there, normally you can't just select {table_name} . It has to be a list of columns. But I am not an expert in MySql - it may allow such trickery. As Jonathan noted below, you'd be better of with:

select table.Time, 'as' from table
union all...

This would definitely bring Time field into the picture.

You need to specify also the Time column in your select

SELECT * from
(SELECT table, Time, 'as'  from as
   UNION ALL
 SELECT table, Time, 'as'  from as
   UNION ALL
 SELECT table, Time, 'as'  from as
   UNION ALL
 SELECT table, Time, 'as'  from as) asAllWrong
 WHERE table not like 'as%' OR length(table) < 12
 ORDER BY Time='2015-06-02 9:00:00' ASC/DESC;

This should work.

EDIT: Thank's for pointing my errors. I just use his example to show it.

Also as other said already you can user select as.*, 'as' from as... this will select all fields from as if you need them of course.

Also you may need ASC or DESC in your ORDER BY clause. ORDER BY sorts the records in ascending order by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM