简体   繁体   中英

MySQL Select column if it exists otherwise select another column

I have multiple databases with the same architecture, same table and column names. With exception, one column name differs among the databases even though the values are the same. I need to write a universal MySQL query which can be applied to all the databases. I need to overcome that one problem where the column name may differ among the databases.

I have tried to lookup the problem in Google and the previous stackoverflow topics, none of them answered to my problem. I tried to solve the problem with 'case when ... then... else' and 'if exists...' statements - doesn't work or I am doing something wrong.

select(case when (select count(*) > 0
    from information_schema.COLUMNS
    where table_name = 'myTable'
    and column_name = 'EUR')
then EUR
else USD
end)
from myTable

I expect to have a working query which checks if the 'EUR' column exists, if it does then select it, and, if it doesn't, then select 'USD' instead.

You can do this as either of:

  1. Use two queries: the first to figure out what column you want to use, then from your software compose a new SQL statement with the correct column to use.
  2. Use server-side Prepared SQL Statements to compose your query from the first query on the server side. See also https://stackoverflow.com/a/986088/53538 as an example.

I'm not sure what you use to run your queries, but if it is any comfortable programing language, there is basically no advantage to approach 2 - its not faster unless your MySQL connection has really large latencies - and it is likely more complicated to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM