Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 SQL Server Administration (2005)
 Table join gone horribly awry

Author  Topic 

logbert
Starting Member

2 Posts

Posted - 2007-08-14 : 09:22:39
Hi all!

I currently have a SQL database that I am having a table join problem with. I'm sure the solution to this is obvious to most people but whatever it is, I'm blind to it.

I have two tables, one called lvl1 and another called lvl2. Rows that are in the lvl1 table can have a relation to each other with a column called parent and there is an id column as well. So if I have a row with an id of 1 and it has 3 child rows, all 3 children have their parent attribute set to "1".

lvl2 has the same properties, except it has a column called lvl1_id which allows it to relate to lvl1 rows. So if a lvl1 row with an ID of 1 has a child in lvl2, the lvl2 row will have a lvl1_id attribute set to "1".

What I am TRYING to do is select all rows in lvl1 with parent = 1 AND all rows in lvl2 with lvl1_id = 1.

This is what my query currently looks like:

SELECT lvl1.*, lvl2.*
FROM lvl1
INNER JOIN lvl2 ON lvl1.id = lvl2.id
WHERE lvl1.parent = '1' OR lvl2.lvl1_id = '1';

This gets the correct lvl1 rows but instead of picking up the correct lvl2 rows, it gives me the lvl1 rows with the same id from the lvl2 rows that it found.

I've played around with the join, swapping lvl1 and lvl2 pretty much everywhere I can but without much luck.

Or am I just going about this all the wrong way?

I've been using databases for a few years now but I've always hated table joins

logbert
Starting Member

2 Posts

Posted - 2007-08-14 : 10:01:31
Ah nevermind this. I realized after the fact that it makes more sense to do a UNION instead of a join since they are two independent sets of data.
Go to Top of Page
   

- Advertisement -