Search code examples
sqlmysqlmysql-error-1054

Handling missing columns in MySQL


Working on parsing a bunch of databases put together in an older, more freewheeling time into a new schema. Basically it's one database per year, with database names like foo98, foo99, foo2000, etc.

So for the most recent foo data, I can do something like

SELECT foo_person.mdname AS middle_name,
...
FROM foo_person, foo_place, foo_thing

As you get back into earlier versions of the foo database, middle name isn't stored. I've tried to build a kind of universal query, something like:

SELECT IFNULL(foo_person.mdname, "") AS middle_name,
...
FROM foo_person, foo_place, foo_thing

but MySQL complains about unknown column foo_person.mdname, which is entirely reasonable as it doesn't exist.

Is there some way to handle non-existent columns with just MySQL syntax, or will I have to write database-specific import queries?


Solution

  • Could you rename the tables and create views in their place with the missing columns?

    Not sure if this is what you're looking for, but thought I would suggest it.

    -- Here is your original table
    create table t (fname varchar(30), lname varchar(30));
    
    -- Rename it to something else
    alter table t rename to tOrig;
    
    -- Create a view with the columns its missing that you need
    create view t as select fname, lname, '' as mname from tOrig;