SQL Select help

I have 2 tables.

table 1
id     name
1      group 1
2      group 2

table 2
id        id of first table
1         1
2         1
3         1

What I would like to do is to SELECT from the first table only if it has records relating to it in the second table. So in the example above, only the record with ID 1 would be seleted.

Any ideas?

Thanks
thomasmuttonAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
RiteshShahConnect With a Mentor Commented:
is this giving you any error?

SELECT pfsog.* FROM Gower_tbl_photosforsaleoptiongroups pfsog
JOIN Gower_tbl_photosforsalegroupoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
0
 
RiteshShahCommented:
select t1.id,t1.name from table1 t1 join table2 t2 on t1.id=t2.IdOfFirstTable
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
You can use the INNER join

SELECT t1.*
FROM Table1 t1
INNER join table2 t2 on t1.ID =t2.iD
0
Easily Design & Build Your Next Website

Squarespace’s all-in-one platform gives you everything you need to express yourself creatively online, whether it is with a domain, website, or online store. Get started with your free trial today, and when ready, take 10% off your first purchase with offer code 'EXPERTS'.

 
RiteshShahCommented:
option 2)


select t1.id,t1.name
from
table1 t1
left outer join
table2 t2 on
t1.id=t2.IdOfFirstTable
where t2.id is not null
0
 
RiteshShahCommented:
aneeshattingal,

I guess join should be on t1.ID =t2.IdOfFirstTable not with t2.id........
0
 
thomasmuttonAuthor Commented:
RiteshShah,

I have tried your second option but it does not deliver distinct records. Should I use a distinct?
0
 
RiteshShahCommented:
you can use it, but what happened to my first query?
0
 
thomasmuttonAuthor Commented:
They have the same outcome
0
 
RiteshShahCommented:
in that case, I recomend you to go for option 1, it is proper method to go.
0
 
thomasmuttonAuthor Commented:
Ok well this is the command I am using.

it does not work.

SELECT * FROM Gower_tbl_photosforsaleoptiongroups pfsog
JOIN Gower_tbl_photosforsalegroupoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
0
 
thomasmuttonAuthor Commented:
Nope, It is getting the right record from table 1 but just repeating it 3 times.
0
 
RiteshShahCommented:
in that case, use DISTINCT....
0
 
thomasmuttonAuthor Commented:
Yeah that worked great.

SELECT DISTINCT pfsog.* FROM Gower_tbl_photosforsaleoptiongroups pfsog
JOIN Gower_tbl_photosforsalegroupoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
0
 
thomasmuttonAuthor Commented:
SELECT DISTINCT pfsog.* FROM Gower_tbl_photosforsaleoptiongroups pfsog
JOIN Gower_tbl_photosforsalegroupoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.