Mysql WHERE有条件的

时间:2013-07-01 10:07:40

标签: mysql conditional

我有一个看起来像下面的表,正如你所看到的,只有名单列表。 有些与其他名称相同。我的目标是,用相同的'firstname'计算每个名字的总数,然后做一些有条件的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    |

1 个答案:

答案 0 :(得分:1)

第一个数据:

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';

然后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