I am trying to write a MYSql query in which I wanth following behaviour:
- fetch position Id from table when the column position_id exists
- set position_id to NULL when the column position_id does not exists in the table.
This is because we want the query to be backward compatible with older versions of our database.
SELECT
DISTINCT(sg.id) as site_group_id,
coalesce(sgd.name, sgdefault.name) as site_group_name,
sg.site_group_type,
sg.term_end,
(SELECT CASE WHEN EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'site_group' AND column_name = 'position_id')
THEN sg.position_id
ELSE NULL
END) as position_id,
sa.site_id
FROM site_group sg
The above solution does not works and Mysql throws an error that Unknown column sg.position_id
in field list