开发者

Query to check if field exists and then return the result set

开发者 https://www.devze.com 2023-02-19 20:50 出处:网络
I dont know how can i explain it, may be this example garbage query can help. SELECT if_exists(Fieldname) * FROM my table name

I dont know how can i explain it, may be this example garbage query can help.

SELECT if_exists(Fieldname) * FROM my table name

I am trying to select all the rows of the database only if Fieldname field is present.

Can yo开发者_如何转开发u help me out


SHOW columns from `yourtable` where field='yourfield'

You will get a empty rows, if you dont have that field in that table.


The following code in plain PHP should work fine:

$chkcol = mysql_query("SELECT * FROM `table_name` LIMIT 1"); 
$mycol = mysql_fetch_array($chkcol); 
if(isset($mycol['column_name'])) 
  $results = mysql_query("SELECT * FROM `table_name`");
else
  $results = false;


IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘you_table_name’ AND COLUMN_NAME = ‘FIELDNAME’)
 BEGIN
    select fieldname from your_table_name
 END


You can use the SHOW COLUMNS expression.

Also i found this solution: http://snippets.dzone.com/posts/show/4663


You need something like this. Sorry, cannot test if the syntax is OK though.

SELECT * FROM table WHERE EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=table AND column_name=column)


Thats a query I used: it returns no column, if the column doesn't exist. It shouldn't be much work to change it, for you needs.

SET @VAR_SQL := Concat('SELECT first_row',CONCAT(IFNULL((SELECT CONCAT(',',COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'my_table' 
AND COLUMN_NAME = 'my_column'),'')),' FROM my_table;');
PREPARE QUERY_STATEMENT FROM @VAR_SQL;
EXECUTE QUERY_STATEMENT;
0

精彩评论

暂无评论...
验证码 换一张
取 消