Damntry Damntry - 2 months ago 23
SQL Question

Column ambiguously defined in subquery using rownums

I have to execute a SQL made from some users and show its results. An example SQL could be this:

SELECT t1.*, t2.* FROM table1 t1, table2 t2, where table1.id = table2.id


This SQL works fine as it is, but I need to manually add pagination and show the rownum, so the SQL ends up like this.

SELECT z.*
FROM(
SELECT y.*, ROWNUM rn
FROM (
SELECT t1.*, t2.* FROM table1 t1, table2 t2, where table1.id = table2.id
) y
WHERE ROWNUM <= 50) z
WHERE rn > 0


This throws an exception: "ORA-00918: column ambiguously defined" because both Table1 and Table2 contains a field with the same name ("id").

What could be the best way to avoid this?

Regards.


  • UPDATE



In the end, we had to go for the ugly way and parse each SQL coming before executing them. Basically, we resolved asterisks to discover what fields we needed to add, and alias every field with an unique id. This introduced a performance penalty but our client understood it was the only option given the requirements.

I will mark Lex answer as it´s the solution we ended up working on.

Lex Lex
Answer

I think you have to specify aliasses for (at least one of) table1.id and table2.id. And possibly for any other corresponding columnnames as well.

So instead of SELECT t1.*, t2.* FROM table1 t1, table2 use something like:

SELECT t1.id t1id, t2.id t2id [rest of columns] FROM table1 t1, table2 t2

I'm not familiar with Oracle syntax, but I think you'll get the idea.