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)

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 に答える