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
 help needed with joins

Author  Topic 

Anterox
Starting Member

4 Posts

Posted - 2010-11-12 : 04:42:12
Hello all. I'm quite new with sql, and have a problem followed.
I have tables A and B, and linktable AB, and i'm stuck with this:

table A
Aid Aname
------------
Aid1 Aname1
Aid2 Aname2
Aid3 Aname3
Aid4 Aname4
Aid5 Aname5

table B
Bid Bname
------------
Bid1 Bname1
Bid2 Bname2
Bid3 Bname3
Bid4 Bname4
Bid5 Bname5

table AB
Aid Bid
------------
Aid1 Bid2
Aid2 Bid2
Aid2 Bid3
Aid2 Bid4
Aid2 Bid5
Aid3 Bid2
Aid3 Bid4
Aid4 Bid1
Aid5 Bid2
Aid5 Bid3
Aid5 Bid4

I need to build dynamically a query to find all members from table A, which have all given values from table B.

So, if i give to B values Bid2,Bid3,Bid4, the result group should be Aid2 and Aid5, which satisfy all the values given from B in linktable.

When i build SELECT with joins, and give WHERE-clause 'WHERE Bid IN (Bid2,Bid3,Bid4)', the result allways includes
values Aid1, Aid2, Aid3 and Aid5, no matter how i build the SELECT clause. And that is not what i want.
Any suggestions and help please?

br
Antero

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-11-12 : 11:30:17
Here is one way, if you need to deal with duplicates (hopefully not) then you will have to adjust the query a bit:
DECLARE @A TABLE (Aid VARCHAR(5), Aname VARCHAR(10))
INSERT @A (Aid, Aname) VALUES
('Aid1', 'Aname1'),
('Aid2', 'Aname2'),
('Aid3', 'Aname3'),
('Aid4', 'Aname4'),
('Aid5', 'Aname5')

DECLARE @B TABLE (Bid VARCHAR(5), Bname VARCHAR(10))
INSERT @B (Bid, Bname) VALUES
('Bid1', 'Bname1'),
('Bid2', 'Bname2'),
('Bid3', 'Bname3'),
('Bid4', 'Bname4'),
('Bid5', 'Bname5')

DECLARE @AB TABLE (Aid VARCHAR(5), Bid VARCHAR(5))
INSERT @AB (Aid, Bid) VALUES
('Aid1', 'Bid2'),
('Aid2', 'Bid2'),
('Aid2', 'Bid3'),
('Aid2', 'Bid4'),
('Aid2', 'Bid5'),
('Aid3', 'Bid2'),
('Aid3', 'Bid4'),
('Aid4', 'Bid1'),
('Aid5', 'Bid2'),
('Aid5', 'Bid3'),
('Aid5', 'Bid4 ')




SELECT
AB.Aid
FROM
@A AS A
INNER JOIN
@AB AS AB
ON A.Aid = AB.Aid
WHERE
AB.Bid IN ('Bid2', 'Bid3', 'Bid4')
GROUP BY
AB.Aid
HAVING COUNT(*) = (SELECT COUNT(*) FROM @B WHERE Bid IN ('Bid2', 'Bid3', 'Bid4'))
Go to Top of Page

Anterox
Starting Member

4 Posts

Posted - 2010-11-19 : 05:04:55
Having hands on in other things, i had time to check this out not until today. But it looks like a solution to my issue, so thank You very much!
Go to Top of Page
   

- Advertisement -