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?
 
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
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
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
All Courses

From novice to tech pro — start learning today.