MySQL SELECT field as NULL if it does not exist in the table

I like to use SELECT in a table, which may contain some field, but maybe not. If not, the value can be returned as NULL, for example JOIN LEFT, for non-existing strings.

Eg. something like this pseudo-sql:

SELECT id, email IF EXISTS, name, address FROM users;

should start without errors on the "users" of the table without the "email" field, but instead return email = NULL.

+5
source share
1 answer

What you want can be done not in pure SQL.

Essentially, you need SQL that can conditionally select a column that may not exist. Such SQL cannot be parsed - all selected columns must exist or the query will be invalid.

, , , , SQL.

:

select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'users'
and TABLE_SCHEMA = 'YOUR-DB-NAME';
+2

All Articles