Hi,
I have this sample table:
CREATE TABLE `dummy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) NOT NULL,
`pet` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `dummy` (`id`, `userId`, `pet`) VALUES(1, 1, 'dog');
INSERT INTO `dummy` (`id`, `userId`, `pet`) VALUES(2, 1, 'cat');
INSERT INTO `dummy` (`id`, `userId`, `pet`) VALUES(3, 2, 'dog');
INSERT INTO `dummy` (`id`, `userId`, `pet`) VALUES(4, 2, 'cat');
INSERT INTO `dummy` (`id`, `userId`, `pet`) VALUES(5, 3, 'cat');
INSERT INTO `dummy` (`id`, `userId`, `pet`) VALUES(6, 4, 'dog');
How can I write the statements below in mysql:
- Retrieve all users who own both a dog and a cat
- Retrieve all users who own a dog or a cat
- Retrieve all users who own only a cat
- Retrieve all users who doesn't own a cat
EDIT: With the help of dbemerlin, I have solutions for first two statements. Here they are:
Retrieve all users who own both a dog and a cat:
SELECT * FROM dummy WHERE pet = 'cat' OR pet = 'dog' GROUP BY userId HAVING COUNT(*) = 2
Retrieve all users who own a dog or a cat:
SELECT * FROM dummy WHERE pet = 'cat' OR pet = 'dog' GROUP BY userId
I have found a solution for 3:
Retrieve all users who own only a cat:
SELECT * FROM dummy WHERE userId IN (SELECT userId FROM dummy WHERE pet = 'cat' GROUP BY userId) GROUP BY userId HAVING COUNT(*) = 1
But Adriano have a better solution:
SELECT * FROM dummy WHERE pet = 'cat' AND userId NOT IN (SELECT userId FROM dummy WHERE pet != 'cat');
But still having problems for the last statement:
Retrieve all users who doesn't own a cat:
SELECT * FROM dummy WHERE pet != 'cat' GROUP BY userId
This doesn't work either. What I exactly need is that to retrieve all user who doesn't own a cat but may have other pets.
Thanks!
EDIT: This is not a homework assignment. I tried to simplify the question for asking here and also to isolate the problem. The real situation is I am trying to retrieve users who have click 2 different links (stored as url strings) and etc. And if this was a homework assignment, what's the wrong in asking how to achieve this here? If I had a friend of mine who had MySQL knowledge, what's the difference asking him to tell me the solution and explain than asking here?