The design looks fine from here. I think Nazim has interpreted your question differently, but the way I read it was that you wanted the combinations of buyers and books such that the set of buyer's domains = set of book's domains. I can't help thinking this is a sub-optimal solution, but it does work:SELECT byid, bkidFROM ( SELECT b1.byid, b1.domainid, COUNT(*) dcount FROM Buyer b1 INNER JOIN Buyer b2 ON b1.byid = b2.byid GROUP BY b1.byid, b1.domainid) BuyerINNER JOIN ( SELECT b1.bkid, b1.domainid, COUNT(*) dcount FROM BOOKS b1 INNER JOIN BOOKS b2 ON b1.bkid = b2.bkid GROUP BY b1.bkid, b1.domainid) Books ON Buyer.domainid = Books.domainid AND Buyer.dcount = Books.dcountGROUP BY byid, bkidHAVING COUNT(*) = MAX(Books.dcount)
Hmm. Perhaps better to flatten out the subqueries: that way the optimizer seems to be able to build a plan without sorts (assuming pks on Buyers (byid, domainid) and BOOKS (bkid, domainid)). See if this is any better (or worse!)SELECT by1.byid, bk1.bkidFROM Buyer by1INNER JOIN BOOKS bk1 ON by1.domainid = bk1.domainidINNER JOIN ( SELECT byid, COUNT(*) bycount FROM Buyer GROUP BY byid) by2 ON by1.byid = by2.byidINNER JOIN ( SELECT bkid, COUNT(*) bkcount FROM BOOKS GROUP BY bkid) bk2 ON bk1.bkid = bk2.bkid AND bycount = bkcountGROUP BY by1.byid, bk1.bkidHAVING COUNT(*) = MAX(bycount)
Edited by - Arnold Fribble on 01/31/2002 05:48:30