在单表MySQL中获取计数

时间:2013-06-03 21:55:14

标签: mysql

我需要获得所有拥有多个成员的俱乐部的Club_ID;

这是sql:

CREATE  TABLE `Members` (
  `ID` INT NOT NULL AUTO_INCREMENT ,
  `Club_ID` INT NULL ,
  `Name` VARCHAR(45) NULL ,
  PRIMARY KEY (`ID`) );


INSERT INTO `Members` (`Club_ID`, `Name`) VALUES ('1', 'Jim');
INSERT INTO `Members` (`Club_ID`, `Name`) VALUES ('2', 'John');
INSERT INTO `Members` (`Club_ID`, `Name`) VALUES ('1', 'Bill');
INSERT INTO `Members` (`Club_ID`, `Name`) VALUES ('3', 'Stan');
INSERT INTO `Members` (`Club_ID`, `Name`) VALUES ('4', 'David');
INSERT INTO `Members` (`Club_ID`, `Name`) VALUES ('1', 'Tony');
INSERT INTO `Members` (`Club_ID`, `Name`) VALUES ('5', 'Oscar');

这应该只返回Club_ID = 1!

3 个答案:

答案 0 :(得分:1)

  SELECT COUNT(*), Club_ID
    FROM Members
GROUP BY Club_ID
  HAVING COUNT(*) > 1

答案 1 :(得分:1)

select Club_ID from Members group by Club_ID having count(*)>1

答案 2 :(得分:0)

select club_id
from members
group by club_id
having count(distinct id) >= 2