Link to home
Start Free TrialLog in
Avatar of thomasmutton
thomasmuttonFlag for United Kingdom of Great Britain and Northern Ireland

asked on

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
Avatar of RiteshShah
RiteshShah
Flag of India image

select t1.id,t1.name from table1 t1 join table2 t2 on t1.id=t2.IdOfFirstTable
Avatar of Aneesh
You can use the INNER join

SELECT t1.*
FROM Table1 t1
INNER join table2 t2 on t1.ID =t2.iD
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
aneeshattingal,

I guess join should be on t1.ID =t2.IdOfFirstTable not with t2.id........
Avatar of thomasmutton

ASKER

RiteshShah,

I have tried your second option but it does not deliver distinct records. Should I use a distinct?
you can use it, but what happened to my first query?
They have the same outcome
in that case, I recomend you to go for option 1, it is proper method to go.
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
ASKER CERTIFIED SOLUTION
Avatar of RiteshShah
RiteshShah
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Nope, It is getting the right record from table 1 but just repeating it 3 times.
in that case, use DISTINCT....
Yeah that worked great.

SELECT DISTINCT pfsog.* FROM Gower_tbl_photosforsaleoptiongroups pfsog
JOIN Gower_tbl_photosforsalegroupoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
SELECT DISTINCT pfsog.* FROM Gower_tbl_photosforsaleoptiongroups pfsog
JOIN Gower_tbl_photosforsalegroupoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id