Solved

SQL Query

Posted on 2013-11-08
3
215 Views
Last Modified: 2013-11-11
I want to write a query that selects multiple columns from one table and 1 column from another table.  Both tables have the same primary key.  

Also, Im not sure if it makes a difference but, the 1 column I want to select from the second table also happens to be the foreign key on the second table (it doesnt exist on the first table).


Can you give me simple syntax for this query?
0
Comment
Question by:tike55
3 Comments
 
LVL 29

Assisted Solution

by:Paul Jackson
Paul Jackson earned 167 total points
ID: 39635095
It would be easier if you posted the structure of the two tables fully but basically it would be something like :

Select a.column1, a.column2, a.column3, b.column2
From table1 a, table2 b
Where a.column1 = b.column1

The above select assumes that column1 in each table is the primary key that exists in both tables.
The 'a' and 'b' prefixes refer to the aliases used for the tables as specified in the from clause.
The which clause provides the join between the two tables on the shared primary key.
The required field in Table 2 is referenced in the Select list as b.Column2 which is an alias for table2.Column2
0
 
LVL 92

Assisted Solution

by:Patrick Matthews
Patrick Matthews earned 166 total points
ID: 39635106
While jacko72's code will work, in SQL Server it is more common to use the join syntax:

Select a.column1, a.column2, a.column3, b.column2
From table1 a inner join table2 b on a.column1 = b.column1
0
 
LVL 32

Accepted Solution

by:
awking00 earned 167 total points
ID: 39635902
select a.col_x, a.col_y, a.col_z, b.fk
from tablea a inner join tableb b
on a.pk = b.pk
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question