10

I have a script where a user can select a field across multiple tables. It uses a Union to get all of the rows. Right now, I have a mapping array to indicate whether a specific field exists in each table, and if it doesn't, it uses "" as field_name to keep everything in check.

I was wondering if there is a way to reference a possibly non-existent column in a query, something like COALESCE so that if the column doesn't exist, instead of throwing an error, it just returns a default value.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
Anthony
  • 36,459
  • 25
  • 97
  • 163

1 Answers1

3

coalesce would still require a fieldname, so it wouldn't help:

... COALESCE(non_existent_field, NULL)

will still cause an error due to the field not existing.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • So I've noticed. All googling suggests that this isn't an option. I was really hoping for a "if exists" type of thing. – Anthony Jul 12 '11 at 18:46
  • You could join in information_schema.tables and base off that ,but seems like a lot of work for not enough gain. – Marc B Jul 12 '11 at 18:48
  • Basically, I'm trying to avoid having to build out logic for adding new custom fields. On the front end, it goes through and looks for all available custom fields (outside of those already available in the mapping array), and it allows the user to select the custom field. But on submit, I then have to do the same thing again to find out which table the field belongs to or if it exists across multiple tables. It would be so much easier if it would just return nothing if the field didn't exist. But I guess that's not an option. – Anthony Jul 12 '11 at 18:51