I am looking to select the id of a record from @table1 when that record is the only record in that table and is not currently linked in @t1Tot2 to a particular id from another table.

The following query below works, but I am wondering if there is a better way. It is setup to currently to return 55 the id of the only record added to table @table1. Inserting another record into @table1 would cause it to return no records ( good ), and linking @t2id in @t1Tot2 would make it return none as well ( good ). Is there a better way? Thanks.

```
DECLARE @t2id INT
SET @t2id = 1 --Record to link to
DECLARE @table1 TABLE
(
t1id int
)
DECLARE @t1Tot2 TABLE
(
t1id INT,
t2id int
)
INSERT INTO @table1
( t1id )
VALUES  ( 55  -- t1id - int
)

--Will cause the query below to return no records because of having more than 1 record to be linked to
--  INSERT INTO @table1
--        ( t1id )
--VALUES  ( 2  -- t1id - int
--          )    

--Will cause the query below to return no records because of already being linked to the t1id
--INSERT INTO @t1Tot2
--( t1id, t2id )
--VALUES  ( 55, -- t1id - int
--@t2id  -- t2id - int
--)    

SELECT MAX(a.t1id)
FROM @table1 a
LEFT JOIN @t1Tot2 b ON a.t1id = b.t1id AND b.t2id = 1
HAVING COUNT(1) = 1 AND SUM( CASE WHEN b.t2id IS NULL THEN 0 ELSE 1 END ) = 0

```