Topic: SQL join question

Just wondering what would be returned from something like the following:

SELECT a.id, b.id FROM a.table AS a LEFT JOIN b.table AS b on b.id=a.id WHERE [rest of query here...]

if the first table, a, had only one column which matched the WHERE clause, but table b had, for example, three columns which matched the a columns id, would you have three rows returned or just one?

Ones mind is just failing to grasp basic logic completely again at the moment. big_smile

Cheers.

Re: SQL join question

if the first table, a, had only one column which matched the WHERE clause

You mean row. wink

And the query would return 3 rows if the row in A that matched the WHERE clause joined to 3 rows in B. If it didn't, it would return 1.

Re: SQL join question

Smartys wrote:

if the first table, a, had only one column which matched the WHERE clause

You mean row. wink

I'll blame it on the mind being in complete go slow mode at the moment. big_smile


Smartys wrote:

And the query would return 3 rows if the row in A that matched the WHERE clause joined to 3 rows in B. If it didn't, it would return 1.

Cheers. smile Thought that was the case. In that case, is there any way to make it only return the first matching row from table b rather than all three when using joins?

Edit: Would using something like 'SELECT DISTINCT(a.id)' do it?

Last edited by MattF (2008-07-17 03:34:12)

Re: SQL join question

Distinct isn't really the way to go. It'd probably be better to use GROUP BY.

SELECT a.id, b.id FROM a.table AS a LEFT JOIN b.table AS b on b.id=a.id WHERE [rest of query here...] GROUP BY a.id

Ben
SVN repository for my extensions - The thread
Quickmarks 0.5
“Question: How does a large software project get to be one year late? Answer: One day at a time!” - Fred Brooks

Re: SQL join question

PgSQL is an absolute dog where GROUP BY is concerned. I think you have to name every column explicitly when you use it with a join, (or something as quirkily annoying). I like PgSQL, but it does have some extreme annoyances on occasion. big_smile

I'm beginning to think it might be simpler to just add an extra column to the first table to achieve what I need.

Re: SQL join question

I'm assuming that you have both tables in same database.

I hope this query will work fine.

SELECT a.id, b.id FROM table1 AS a LEFT JOIN table2 AS b on b.id=a.id WHERE [rest of query here...]

Re: SQL join question

sandeep.kumar wrote:

I'm assuming that you have both tables in same database.

I hope this query will work fine.

SELECT a.id, b.id FROM table1 AS a LEFT JOIN table2 AS b on b.id=a.id WHERE [rest of query here...]

Sorry, but you have missed the point of the topic. wink

Re: SQL join question

I do not know why you would use GROUP BY unless you are using something like SUM or COUNT. You said you just need the first row in b that matches a so why not a subquery with limit 1?

SELECT a.id, (SELECT b.id FROM b WHERE b.id = a.id LIMIT 1) FROM a WHERE ...