I have a mysql table which holds lots of data across multiple tables. So to get it all out, I think the best bet is to use a UNION clause, however I also want to know which table the results come from as some have multiple values and some are null.
The following sql does not appear to work but I cant see whats wrong.
(SELECT *, `2` AS 'cat' from `2` where `recid` = 'cneta0ld00ah')
UNION
(SELECT *, `3` AS 'cat' from `3` where `recid` = 'cneta0ld00ah')
UNION
(SELECT *, `4` AS 'cat' from `4` where `recid` = 'cneta0ld00ah')
UNION
(SELECT *, `5` AS 'cat' from `5` where `recid` = 'cneta0ld00ah')
All Tables look something like the following are are named, 1, 2, 3, 4 etc.
recid | item
-------------------------
cneta0ld00ah | 1
cneta0ld00ab | 1
cneta0ld00ad | 3
I cant change the name of the tables as its an import from a very old database which we are trying to convert and extract data from.
If I run it without the ‘table-name’ AS ‘cat’, then it runs fine, as soon as I try to add in the table name it throws an error saying
Unknown column '2' in 'field list'
It seems to be thinking 2 is a column name?
The problem is the backticks you have around the ‘table-name’ AS ‘cat’. Backticks are for quoting table and column names, not strings. You should use single quotes instead: