How can I check if mysql table column even exists?

后端 未结 8 943
闹比i
闹比i 2020-12-30 08:44

How can I check if mysql table field even exists ?

The column name is \'price\' and I need to see if it exists.

Haven\'t understood really how the \'EXISTS\'

相关标签:
8条回答
  • 2020-12-30 08:54

    Try:

    IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'TEST' AND COLUMN_NAME = 'Price')
    BEGIN
        -- do something, e.g.
        -- ALTER TABLE TEST ADD PRICE DECIMAL
    END
    
    0 讨论(0)
  • 2020-12-30 08:55

    You could get a description of all the column in your table.

    desc your_table;

    0 讨论(0)
  • 2020-12-30 08:56

    In PHP:

    $fields = mysql_list_fields('database_name', 'table_name');
    $columns = mysql_num_fields($fields);
    for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
    
    if (!in_array('price', $field_array))
    {
    $result = mysql_query('ALTER TABLE table_name ADD price VARCHAR(10)');
    }
    

    This should also help you:

    IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = ‘TEST’ AND COLUMN_NAME = ‘TEST_DATE’)
    BEGIN
      ALTER TABLE TEST ADD TEST_DATE DATETIME
    END
    

    Or you can do:

    Show columns from table like 'string';
    

    There has been a similar question posed on SO here before.

    0 讨论(0)
  • 2020-12-30 09:02

    Well, one way is to do:

    select price from your_table limit 1
    

    If you get an error:

    #1054 - Unknown column 'price' in 'field list'
    

    then it does not exists.

    0 讨论(0)
  • 2020-12-30 09:10

    Another way of doing it in PHP:

    $chkcol = mysql_query("SELECT * FROM `table_name` LIMIT 1"); 
    $mycol = mysql_fetch_array($chkcol); 
    if(isset($mycol['price'])) 
      echo "Column price exists! Do something...";
    
    0 讨论(0)
  • 2020-12-30 09:10

    I found this very useful. It will list all the tables that has that column name.

    SELECT table_name, 
           column_name 
    FROM   information_schema.columns 
    WHERE  column_name LIKE '%the_column_name%' 
    
    0 讨论(0)
提交回复
热议问题