Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 select if it exists in another table?

Author  Topic 

arya6000
Starting Member

3 Posts

Posted - 2010-12-28 : 03:11:35
Hello

I have 2 tables

table1 which one of its columns is called 'host' (this table can contain multiple hosts)
table2 which has a 'host' column as its primary key.

I want to make a query that selects one host from table1 if it does not belong in table2 already.

I've tried many things and so far I know I have to SELECT DISTINCT with LIMIT 1, but other than that, not sure how to do it. Is this even possible with the way I have my DB setup?

Regards!

Devart
Posting Yak Master

102 Posts

Posted - 2010-12-28 : 03:54:50
For example:

SELECT DISTINCT table1.host
FROM table1 LEFT JOIN table2 ON table1.host=table2.host
WHERE table2.host IS NULL;

Devart,
SQL Server Tools:
dbForge Data Studio
dbForge Schema Compare
dbForge Data Compare
dbForge SQL Complete
Go to Top of Page

Sachin.Nand

2937 Posts

Posted - 2010-12-28 : 04:09:02
try this
select host from table1 t1 where not exists(select 1 from table2 t2 where t1.host=t2.host)


Also are you using SQL server?

PBUH

Go to Top of Page

arya6000
Starting Member

3 Posts

Posted - 2010-12-28 : 04:12:26
Thanks to both of you, its working now, I'm using PostgreSQL
Go to Top of Page

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2010-12-28 : 05:14:47
This is a SQL Server forum, we're going to assume that questions are related to SQL Server. PostgreSQL has different syntax, different rules and anything we suggest that will work for SQL may not work for that.
Suggest you post PostgreSQL questions on a PostgreSQL forum in future.

--
Gail Shaw
SQL Server MVP
Go to Top of Page
   

- Advertisement -