Home > Mobile >  SQL Query between two tables and only return entries from one table
SQL Query between two tables and only return entries from one table

Time:07-21

I'm looking to create a query between two tables but only matches from one specific table. This is what I've tried so far

SELECT DISTINCT *
FROM dbo.table1, dbo.table2
WHERE dbo.Table1.Field1 = dbo.Table2.Field1

It's currently returning many duplicates and a ton of records that don't even meet the matching criteria. I only want to return matches from Table1 that meet the criteria

CodePudding user response:

Try

SELECT DISTINCT [t1].*
FROM [dbo].[table1] [t1]
JOIN [dbo].[table2] [t2] ON [t2].[Field1] = [t1].[Field1];

CodePudding user response:

It sounds like your join is duplicating rows, if you want to return columns from table1 only then possibly you need to use exists:

select <columns>
from dbo.table1 t1
where exists (select * from dbo.table2 t2 where t2.field1 = t1.field1);

CodePudding user response:

SELECT 
DISTINCT t1.* -- or list of columns from table1 instance(t1)
FROM 
    dbo.table1 as t1 
left join
    dbo.table2 as t2
ON dbo.t1.Field1 = dbo.t2.Field1;

See the different types of joins and use the appropriate one that matches with your scenario.

  • Related