thomasmutton
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
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
select t1.id,t1.name from table1 t1 join table2 t2 on t1.id=t2.IdOfFirstTable
You can use the INNER join
SELECT t1.*
FROM Table1 t1
INNER join table2 t2 on t1.ID =t2.iD
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
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........
I guess join should be on t1.ID =t2.IdOfFirstTable not with t2.id........
ASKER
RiteshShah,
I have tried your second option but it does not deliver distinct records. Should I use a distinct?
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?
ASKER
They have the same outcome
in that case, I recomend you to go for option 1, it is proper method to go.
ASKER
Ok well this is the command I am using.
it does not work.
SELECT * FROM Gower_tbl_photosforsaleopt iongroups pfsog
JOIN Gower_tbl_photosforsalegro upoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
it does not work.
SELECT * FROM Gower_tbl_photosforsaleopt
JOIN Gower_tbl_photosforsalegro
pfsog.pfsog_Id = pfsgo.pfsog_Id
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Nope, It is getting the right record from table 1 but just repeating it 3 times.
in that case, use DISTINCT....
ASKER
Yeah that worked great.
SELECT DISTINCT pfsog.* FROM Gower_tbl_photosforsaleopt iongroups pfsog
JOIN Gower_tbl_photosforsalegro upoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
SELECT DISTINCT pfsog.* FROM Gower_tbl_photosforsaleopt
JOIN Gower_tbl_photosforsalegro
pfsog.pfsog_Id = pfsgo.pfsog_Id
ASKER
SELECT DISTINCT pfsog.* FROM Gower_tbl_photosforsaleopt iongroups pfsog
JOIN Gower_tbl_photosforsalegro upoptions pfsgo ON
pfsog.pfsog_Id = pfsgo.pfsog_Id
JOIN Gower_tbl_photosforsalegro
pfsog.pfsog_Id = pfsgo.pfsog_Id