Joining tables without a primary key
Can you solve this in MS SQL-Server with the help of a SQL query. The scenario is as follows:
Table A ======= Code Name CE Java CE Oracle CE Microsoft AE Sun AE Digital AE HP AR Compaq Table B ======= Code Location CE US CE UK AE Japan
Now with the help of SQL query, please produce the output:
----------------------------------------------------- Code Name Location ----------------------------------------------------- CE Java US CE Oracle UK CE Microsoft NULL AE Sun Japan AE Digital NULL AE HP NULL AR Compaq NULLCommon field is Code between both the tables. But none of the tables has a Primary Key.
A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.
To do this you use an outer join:
select tablea.code, tablea.name, tableb.location from tablea left outer join tableb on tablea.code = tableb.code
For More Information
- What do you think about this answer? E-mail us at [email protected] with your feedback.
- The Best Microsoft SQL Server Web Links: tips, tutorials, scripts, and more.
- The Best SQL Web Links
- Have a SQL Server 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 Server 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.