ResultSetMetaData.getColumnName returns different values for UNION and non-UNION queries

StackOverflow https://stackoverflow.com/questions/23679324

  •  23-07-2023
  •  | 
  •  

Pregunta

Using Java JDBC, I want to collect information returned from SQL Select query.

If I fire below SQL query:

SELECT col1 AS 'Field1', col2 AS 'Field2' FROM Table;

Then, using resultSetMetaData.getColumnName(1), I get 'col1' as result, which is the expected result.

Now, the problem is, when I join 2 SQL tables (Since, MySQL does not provide Full Outer Join, hence, I fired the following query)

SELECT Table1.Col1 AS 'Field1', Table1.Col3 AS 'Field2',
Table2.Col5 AS 'Field3',Table2.Col4 AS 'Field4' FROM Table1 
LEFT JOIN Table2 ON Table1.id = Table2.id 
UNION 
SELECT Table1.Col1 AS 'Field1', Table1.Col3 AS 'Field2', 
Table2.Col5 AS 'Field3',Table2.Col4 AS 'Field4' FROM Table1 
RIGHT JOIN Table2 ON Table1.id = Table2.id;

Now, using resultSetMetaData.getColumnName(1), I get 'Field1' as result, where as, I expected 'col1'.

I tried resultSetMetaData.getColumnLabel(1) also, but it still returned 'Field1'.

I want 'col1' as the result, which I could not get by any of the methods of resultSetMetaData.

Any help on this will be appreciable.

¿Fue útil?

Solución

You are seeing those results because it is a UNION query. It is entirely possible that such a query could do something like

SELECT Col1 AS Field1 FROM Table1
UNION
SELECT Col2 AS Field1 FROM Table2

In that case there is no single "correct" answer if getColumnName was to try and return the name of the underlying column in the result: Should it return 'Col1' or 'Col2'?

Since any column in the result set of a UNION query can be derived from more than one underlying column, getColumnName can only return the effective name of that column, which is Field1 in the example above.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top