Question

I want to check, if a column (mysql) exists. If not, mysql should take the value from a column that definitely exists. My Query looks like this, but it does not work:

IF NOT EXISTS (SELECT `en` FROM `HP_strings` 
               WHERE `name`='copyright' AND `group`='system')
THEN
    SELECT `default` FROM `HP_strings` 
    WHERE `name`='copyright' AND `group`='system';

I also tried

IFNULL((SELECT `en` FROM `HP_strings` 
        WHERE `name`='copyright' AND `group`='system'),
(SELECT `default` FROM `HP_strings` 
 WHERE `name`='copyright' AND `group`='system'));

Same result (error)

EDIT: 'en' does NOT EXIST. I want to know, if it exists.

Was it helpful?

Solution

To inspect a table structure in MySQL, you have to query the information_schema database. To do that, your db user must have access to that system database (which a regular user shouldn't have).

I don't know what you are trying to do, but you should probably rethink you database structure so it doesn't require checking if a column exists in a table.

OTHER TIPS

Try this:

SELECT `default` FROM `HP_strings` where isnull(`en`) and `name`='copyright' 
AND `group`='system'

EDIT: (Based on your comment)

You can check whether a column really exist or not in your table from DB schema like below ... but I don't think you can manipulate in your query like you are intending to.

SELECT *  FROM information_schema.COLUMNS  
WHERE TABLE_SCHEMA = 'db_name'  
AND TABLE_NAME = 'table_name'  
AND COLUMN_NAME = 'column_name' 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top