0

使用表别名连接后如何区分不同表的属性?

作为一个简化的示例,我有两个具有很多属性的表,属性名称不是唯一的,两个表都有id- 例如。

现在 - 我有以下示例性查询:

SELECT * FROM tableA ta INNER JOIN tableB tb ON ta.id = tb.a_id

如何获得两个“id”属性的值?

以下没有奏效:

def sql = Sql.newInstance("jdbc:mysql://${MYSQL_SERVER}/${MYSQL_TABLE}", MYSQL_USER, MYSQL_PASSWORD, "com.mysql.jdbc.Driver")
sql.eachRow (query){ row ->
    println "ID of the 'table a object' : ${row['ta.id']}"
    println "ID of the 'table b object' : ${row['tb.id']}"
}

有了这个,我得到以下错误:java.sql.SQLException: Invalid column name ta.id

我的临时(但不希望)解决方案是在查询中指定属性:

SELECT ta.id as aID, tb.id as bID, * FROM tableA ta INNER JOIN tableB tb ON ta.id = tb.a_id

两者tableA都有tableB很多属性 - 可能重复 - 我不想分别不能手动指定。

我该怎么做才能让它发挥作用?

4

1 回答 1

1

I have a working example of what you are explaining:

sql.eachRow("select * from Group_ G inner join Organization_ O on G.name = O.organizationId")  { row ->
    println "${row['G.name']} ${row['O.name']}"
}

From your code, what I see is that:

ON ta.id = tb.a_id

are not the same properties you are trying to access:

row['ta.id']
row['tb.id'] // tb.a_id?
于 2012-05-07T14:21:50.700 回答