Reputation: 435
I have a SQL query:
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID = '101'
The above query runs fine.
I want to have results for email addresses, for which TableID has different values like 123,421.
So, when I write the following query, why do I get 0 result returned in MySQLWorkbencch?
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID = '101'
AND TableId = '123'
AND TableID = '421'
Upvotes: 0
Views: 566
Reputation: 18600
Try with either OR
or IN
clause. AND
returns records when all specified condition is true which is not happen in your case that's why return 0 result or empty result.
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID = '101'
OR TableId = '123'
OR TableID = '421';
OR
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID IN('101','123','421');
Upvotes: 0
Reputation: 9894
USE IN or OR
By using OR:
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID = '101'
OR TableId = '123'
OR TableID = '421'
By using IN:
SELECT COUNT(DISTINCT(EMAIL_ADDRESS))
FROM MYTABLE
WHERE TABLEID IN ('101','123','421');
Explanation:
'Dog is equals to Dog AND
Dog is equals to Cat AND
Dog is equals to Cow'
Which returns false
'Dog is equals to Dog OR
Dog is equals to Cat OR
Dog is equals to Cow'
Which returns true
'Is Dog available in list containing Dog, Cat, Cow'
Which returns true
Upvotes: 2
Reputation: 97130
Use OR
instead of AND
. Using AND
, you're requiring a column value to be equal to 3 different constant values. This violates the laws of the universe.
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID = '101' OR TableId = '123' OR TableID = '421';
Alternatively, you can use the IN
clause. In terms of actual execution they're equivalent, but in some cases IN
might be easier to read, especially if the list gets longer:
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID IN ('101', '123', '421');
Upvotes: 5
Reputation: 2501
Use IN Clause instead.
SELECT count(DISTINCT(email_address))
FROM Mytable
WHERE TableID IN ('101','123','421')
Upvotes: 2