Table Joins

They have: 10 posts

Joined: Oct 1999

Say I have a key in a table... and another table that links the key to more data.

I want to do a select where the Key is replaced with a feild from the other data. I think this is called a table join, I know this is the heart of a relational database but am not sure how to do it with an sql query.

Thanks

Peter J. Boettcher's picture

They have: 812 posts

Joined: Feb 2000

PDavis,

Joins can be done in different ways (and in different ways on different database servers) so it can get a little tricky.

Lets say you had a database called People and a table called Person with the following columns:

Person_ID
Person_FirstName

and you had a table called Books with the following columns:

Book_PersonID
Book_Name

You could use a SQL statement like:

USE People
SELECT p.Person_ID, p.Person_FirstName, b.Person_ID, b.Book_Name
FROM Person AS p LEFT OUTER JOIN Books AS b
ON p.Person_ID = b.Person_ID

Or you could write a SQL statement like:

USE People
SELECT p.Person_ID, p.Person_FirstName, b.Person_ID, b.Book_Name
FROM Person AS p, Books AS b
WHERE p.Person_ID *= b.Person_ID

Both those queries would return the same recordset.

PJ | Are we there yet?
pjboettcher.com

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Peter-
is that Access SQL syntax? or perhaps Perl?
I've never seen the USE people before. exept when at the command line for a mySQL DB.

I work primarily with SQL Server 7 and ASP, and we specify the DB in the connection string. All at once.

PHP (with mySQL) is similar to ASP in that you specify the DB before you ever execute a query. But with PHP, you first connect to the server, then select the DB.

Mark Hensler
If there is no answer on Google, then there is no question.

Peter J. Boettcher's picture

They have: 812 posts

Joined: Feb 2000

Max,

That syntax was for SQL Server. You're right, you don't have to specify the database with the USE statement, but you can, I was just trying to be thorough with that example.

PJ | Are we there yet?
pjboettcher.com

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

can you connect to one DB in the connection string (like in ASP), then put "USE db_name" in the query and actually change DBs?
if so, would this change the connection for everything, or just that one query?

this is interesting...

Mark Hensler
If there is no answer on Google, then there is no question.

Peter J. Boettcher's picture

They have: 812 posts

Joined: Feb 2000

Max,

The SQL query still has to correspond with the connection object. So if your connection object uses a database called "TEST" and then you try a statement with "USE NOT_TEST" it will fail.

PJ | Are we there yet?
pjboettcher.com

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

thanks!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.