Use column alias to query same field names
I'm doing a query that scans multiple tables based on certain conditions. My problem is that some of the field names are the same in the result set, and I am unable to reference the particular field I want. I have tried using the syntax "tablename.fieldname" but get an error. If I just put "fieldname" I get the last occurence of that name in the result set.
Alias at least one of the columns using the AS keyword.
select MyTable1.ID as ID1, MyTable2.ID as ID2 from MyTable1, MyTable2 where MyTable.ID = MyTable2.ID
For More Information
- Dozens more answers to tough SQL questions from Jason Law are available here.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.