tags:

views:

71

answers:

3

Hello guys.

My skills with SQL are simple, so i'm not sure how to do this.. Here it goes.

Lets consider this.

Table A
ID              Name              LastNameID
1               Jonh              23
2               Helen             19

Table B
ID              LastName
23              Bauer
19              Summers

.

SELECT ID Name LastNameID FROM TableA

How can i add another Select inside that one that will return the LastName from Table B based on the LastNameID in Table A.

In this case i usually use a simple function with the Programming language that i use to do that for each returned Row.

But i think its time to do that with SQL alone.

Any help is appreciated.

+3  A: 

You just need to join the tables using the LastNameId field:

SELECT TableA.[Name] AS FirstName, TableB.LastName
FROM TableA 
  INNER JOIN TableB ON TableA.LastNameId = TableB.LastNameId
Chris Latta
I'm trying your answers... But now i gotta apply them to do those relations between 4 tables.. It might take a while. Thanks.
Fábio Antunes
A: 

You are asking "how to do it with a select inside select". Usually, such queries are written in the form of joins, not as sub-selects. Doing joins is better than doing sub-selects for small number of tables.

The query for your application would be

SELECT firstNames.Name, lastNames.LastName FROM TableA firstNames, TableB lastNames
WHERE firstNames.LastNameId = lastNames.LastNameId;

This is the same as writing the query in an explicit join form as shown by Chris in his answer.

Here Be Wolves
Thanks for the help. It might do it
Fábio Antunes
A well written database engine will usually plan the queries the same way. But using joins is more idiomatic.
Kyle Butt
jrharshath could you explain how your code worsk? So that i can apply it in big scale in my application. Would this work on Sql Server CE?
Fábio Antunes
A: 

There are some good answers here, but if you actually have the first name in one table and last name in another table linked by an ID - I think it is time to review the basics. Start with looking at the Northwind database andmthen some of the database starter kits here.

JBrooks
I used First and Last Name as the more simple possible.. It was just something it came to my head. I would never do that of course. But the solution would be very good to other situations.
Fábio Antunes