在 2 个表中使用具有相同列名的 ResultSetMetaData

Using ResultSetMetaData with same column name in 2 tables

我想从 2 table 中获取列名,然后使用 ResultSetMetaDataResultSet 获取它们的值。假设 table myTable 有 x、y 和 z 列。我愿意

 Select * from table myTable A,myTable B where A.x = B.y

并且我想在我的代码中使用 B.z 的值。

ResultSetMetaData 会将列列为 x y z x y z ,那么如何区分 z 的值与别名 A 和 B?

我需要在查询中使用 *,因为它可以提高我的性能。所以我不能在那里提到列名。有什么方法可以使用 ResultSet 的列名获取 B.z 列的值吗?我的意思是有什么方法可以让 ResultSetMetaData 将列列为 A.x、A.y、A.z、B.x、B.y 和 [=24] =] ?

看起来更像 JDBC ResultSet get columns with table alias

使用 rs.getMetaData().getTableName(colid) 提供每列的 table 名称,您必须生成自己的哈希图,键为 tablename,值为列名列表。

如果您不能或不想指定列名(使用别名),那么您将需要按索引而不是按列标签检索值。 ResultSet API doc 明确表示:

When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned. The column name option is designed to be used when column names are used in the SQL query that generated the result set. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names are used, the programmer should take care to guarantee that they uniquely refer to the intended columns, which can be assured with the SQL AS clause.

(强调我的)

如果你想区分列,那么你可以使用 ResultSetMetaData.getTableName,但它不会帮助你检索(除了找到要使用的 "right" 索引)。请注意,并非所有数据库都支持提供 table 名称。