Mysql如果列存在,如何仅从列中进行选择 [英] Mysql How to only select from a column if the column exists
问题描述
我需要能够检查列是否存在,如果它存在,那么我想从中进行SELECT。
I need to be able to check if a column exists and if it does then I want to SELECT from it.
我正在尝试很多不同的变体但是我我甚至不确定这是否可能。
I am trying lots of different variations but I'm not even sure if this is possible.
这是我的最新尝试:
SELECT
IF (EXISTS (SELECT `Period` AS `Period` FROM myview), `PERIOD`,
IF (EXISTS (SELECT `Country` AS `COUNTRY` FROM myview),`COUNTRY` FROM myview ;
有任何想法吗?
编辑
我在这里看到了另一个问题:< a href =https://stackoverflow.com/questions/3395798/mysql-check-if-a-column-exists-in-a-table-with-sql> MySQL,检查表中是否存在列SQL
I had seen the other question on here: MySQL, Check if a column exists in a table with SQL
但我仍然在努力使用if语句。我可以使用上面问题中的答案检查列是否存在。但我的问题是 - 如果发现结果为真,如何从该列执行select语句。
But I still struggle with the if statement. I can check to see if the column exists using the answer in the question above. But my question is - how to execute a select statement from that column if the result is found to be true.
编辑2
下面的答案表明我应该使用BEGIN和END语句,这是有道理的。但是,我的查询在第一行抱怨。它说'意外的IF' - 任何人都可以确认这是否是MYSQL的正确语法?
The answer below indicates that I should use the BEGIN and END statement and this makes sense. However, my query complains at the first line. It says 'unexpected IF' - can anybody confirm if this is the right syntax fro MYSQL?
if( exists (SELECT *
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'view_name'
AND COLUMN_NAME = 'column_name') )
begin
SELECT `column_name` FROM `view_name`
end
提前致谢。
推荐答案
此查询将显示列是否存在。
This query will give you whether a column exists.
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name'
如果你想要要检查是否存在某些列然后执行select语句,您需要首先检查列是否存在。然后执行select:
If you want to check if some columns exist then perform a select statement you need to first check your columns exist. Then perform the select:
if (exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'myview' AND COLUMN_NAME = 'Period') and exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'myview' AND COLUMN_NAME = 'Country'))
begin
select `Period`, `Country` from myview
end
如果IF条件为真,那么您将执行BEGIN和END内的任何内容。
If the IF condition is true, then you will execute anything inside the BEGIN and END.
这篇关于Mysql如果列存在,如何仅从列中进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!