views:

94

answers:

2

the following SQL is returning every BT.Bt_Name where L.date_back is Null. I only wish to select the BT.Bt_Names where L.Bc_id is duplicated

SELECT BT.Bt_Name
FROM Book_Title BT INNER JOIN (
    Book_Copy BC INNER JOIN Loan L ON BC.Bc_id = L.Bc_id
)   ON BT.Bt_id = BC.Bt_id
WHERE L.Date_back Is NULL
GROUP BY BT.Bt_name
HAVING COUNT(L.Bc_id) >1;

Is it the joins which are causing COUNT(L.Bc_id) to be >1 for all records where L.Date_back Is NULL? FYI only one should be returned (deliberate input error).

A: 

Yes, you are inadvertently creating a Cartesian product between Book_Title and Loan.

Try this:

HAVING COUNT(DISTINCT BC.Bt_id) > 1
Bill Karwin
hi,MS Access 2007 returns SYNTAX ERROR (MISSING OPERATOR) with that change. Have tried UNIQUE also and same error message. Guess this could be my issue, sadly I must use these products.
AlasdairC
In the future it would help if you mention in your question what technology you're using.
Bill Karwin
Apologies for that, will do in future..
AlasdairC
For the Access Database Engine, you have to do the DISTINCT part in a subquery :(
onedaywhen
A: 

Why bother with the brackets? Why not this?

SELECT BT.Bt_Name, count(*) ct FROM Book_Title BT

INNER JOIN  Book_Copy BC on BT.Bt_id = BC.Bt_id

INNER JOIN Loan L ON BC.Bc_id = L.Bc_id

WHERE L.Date_back Is NULL

GROUP BY BT.Bt_name HAVING COUNT(*) >1;

Or do I have the wrong end of the stick?

Doctor Chris Chris