3

我有以下表格

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8  ;


CREATE TABLE IF NOT EXISTS `skill` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8  ;

CREATE TABLE IF NOT EXISTS `user_skill` (
  `user_id` int(11) NOT NULL,
  `skill_id` int(11) NOT NULL ,
  PRIMARY KEY (`user_id`,`skill_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8  ;

该表user_skill充当多对多表。现在我想选择所有具有至少skill_id1 和 2的用户。我怎样才能在 mysql 中做到这一点

4

2 回答 2

2
select u.id, u.name
from `user` u
inner join `user_skill` us on u.id = us.user_id
where us.skill_id in (1, 2)
group by u.id
having count(distinct us.skill_id) = 2
于 2012-09-13T18:50:33.210 回答
1

天真的方式,使用WHERE EXISTS

SELECT id
FROM `user` u
WHERE EXISTS(SELECT 1 FROM user_skill s WHERE s.user_id = u.id AND s.skill_id = 1)
AND EXISTS(SELECT 1 FROM user_skill s WHERE s.user_id = u.id AND s.skill_id = 2)

使用两个连接:

SELECT u.id
FROM `user` u
INNER JOIN user_skill s1 ON s.user_id = u.id AND s.skill_id = 1
INNER JOIN user_skill s2 ON s.user_id = u.id AND s.skill_id = 2

使用HAVING COUNT

SELECT u.id
FROM `user` u
INNER JOIN user_skill s ON s.user_id = u.id
WHERE s.skill_id IN (1,2)
GROUP BY u.id
HAVING COUNT(*) = 2
于 2012-09-13T18:48:36.350 回答