Something like this is happening:
Persons
table
ID Name
-- ------------
1 John Doe
2 Xaisoft
Colors
table
PersonID ColorName
-------- ---------
1 Red
1 Yellow
2 Yellow
Now query Persons.*
for John Doe
while joining to Colors
:
SELECT p.*
FROM Persons p
INNER JOIN Colors C ON c.PersonID = p.ID
WHERE p.Name = 'John Doe';
Your result will be one p.*
row for each color under John Doe:
ID Name
-- ------------
1 John Doe
1 John Doe
If you apply a COUNT DISTINCT
against this you'll end up with 1
.
If you count Red
and Yellow
separately, you'll get one for each query. Add them up and you'll get 2
.
Look at it this way: if you throw out the COUNT
and just SELECT DISTINCT Persons.*
you get these results:
Red or Yellow for John Doe:
SELECT DISTINCT p.*
FROM Persons p
INNER JOIN Colors C ON c.PersonID = p.ID
WHERE p.Name = 'John Doe'
AND c.ColorName IN ('RED', 'YELLOW');
ID Name
-- ----------
1 John Doe
Red only for John Doe:
SELECT DISTINCT p.*
FROM Persons p
INNER JOIN Colors C ON c.PersonID = p.ID
WHERE p.Name = 'John Doe'
AND c.ColorName IN ('RED');
ID Name
-- ----------
1 John Doe
Yellow only for John Doe:
SELECT DISTINCT p.*
FROM Persons p
INNER JOIN Colors C ON c.PersonID = p.ID
WHERE p.Name = 'John Doe'
AND c.ColorName IN ('YELLOW');
ID Name
-- ----------
1 John Doe