Jump to content

[SOLVED] Bringing back the right results with LEFT JOIN


Recommended Posts

I am hoping this makes sense once i write it down... here goes...

 

table1

---------------

id      name

1      one

2      two

3      three

 

table2

------------

id        type

1          1

1          2

2          1

3          2

Bringing back distinct records with a type of 1

SELECT Distinct(id), name, type FROM table1 LEFT JOIN table2 ON table2.id = table1.id WHERE table2.type = 1

 

brings back......

 

id     name      type

1      one          1

2      two          1

 

 

This is ok..However.... i now want to bring back the distinct id's that have types of both 1 and 2

 

SELECT Distinct(id) FROM table1 LEFT JOIN table2 ON table2.id = table1.id WHERE table2.type = 1 AND table2.type = 2

 

This brings back 0 records

 

 

using OR brings back records with either

SELECT Distinct(id) FROM table1 LEFT JOIN table2 ON table2.id = table1.id WHERE table2.type = 1 OR table2.type = 2

 

id     name

1      one   

2      two

3      three

 

 

i am looking to only return the result

 

id     name

1      one   

 

as this is the only one who has a  joined record with both 1 and 2

 

 

 

 

Thanks in Advance.

 

Hi

 

Your trouble is that you are trying to check to returned rows at once. You really need both matches returned on one row.

 

An example way to do it (and just using a normal join rather than an outer join).

 

SELECT Distinct(a.id)

FROM table1 a

JOIN table2 b ON b.id = a.id AND b.type = 1

JOIN table2 c ON c.id = a.id AND c.type = 2

 

All the best

 

Keith

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.