-2

我有一张如下表所示的表格,如您所见,只有名称列表。有些与其他名称相同。我的目标是,用相同的“名字”计算每个名字的总数,然后做一些条件,比如 IF(total_of_firstname >= 1 && total_of_firstname <= 20)。显示结果。如何仅使用 MySQL 来实现这一点?

|    id     |   firstname     |    lastname    |
|     1     |   Bob           |    Smith       |
|     2     |   Bob           |    Marley      |
|     3     |   Stacey        |    Clarke      |
|     4     |   Stacey        |    Witson      |
|     5     |   Stacey        |    Kowalowski  |
|     6     |   George        |    Benington   |
|     7     |   George        |    Robinson    |
4

1 回答 1

1

First data:

CREATE TABLE `table`
 ( id int(11) auto_increment,
   firstname text, 
  lastname text,
  primary key (`id`)
 );


INSERT INTO `table` SET
 firstname = 'a',
 lastname = 'b';

INSERT INTO `table` SET
 firstname = 'a',
 lastname = 'c';

INSERT INTO `table` SET
 firstname = 'b',
 lastname = 'c';

INSERT INTO `table` SET
 firstname = 'c',
 lastname = 'c';

INSERT INTO `table` SET
 firstname = 'a',
 lastname = 'c';

Then SQL:

SELECT tablegrouped.firstname, tablegrouped.firstnamecount
FROM (
 SELECT firstname, count(*) as firstnamecount
 FROM table
 GROUP BY firstname) AS tablegrouped
WHERE tablegrouped.firstnamecount >=1 AND tablegrouped.firstnamecount <=20
于 2013-07-01T10:17:19.950 回答