0

假设有 2 个表:

TABLE: team
-----------
| team_id |
===========
| 1       |
-----------
| 2       |
-----------

TABLE: team_member
-------------------------------------------
| team_member_id | team_id | age | gender |
===========================================
| 1              | 1       | 20  | Male   |
-------------------------------------------
| 1              | 2       | 25  | Male   |
-------------------------------------------
| 1              | 2       | 23  | Female |
-------------------------------------------

我如何搜索这样的东西:

  1. 年龄在 18 至 25 岁之间的所有男性团队列表。
  2. 所有男性和女性团队的列表,其中任一性别在 18 至 25 岁之间。
  3. 等等。

我基本上是在寻找有关如何在所有子记录中应用某些过滤器(例如年龄)的一般策略team。建议?

4

4 回答 4

1

团队,团队成员

如果您只检查全男性或全女性团队,则不能只应用一个简单的 WHERE 子句……需要将其与所有团队成员进行比较。尝试

select 
      tm.team_id,
      sum( if( tm.gender = 'Male' AND tm.age between 18 and 25, 1, 0 )) as MaleInRange,
      count(*) AllTeamMembers
  from
      team_member tm
  group by
      tm.Team_ID
  having
      MaleInRange = AllTeamMembers

同样,为了确保你有男性和女性......

select 
      tm.team_id,
      sum( if( tm.age between 18 and 25, 1, 0 )) as AgeInRange,
      sum( if( tm.gender = 'Male', 1, 0 )) as MaleCnt,
      sum( if( tm.gender = 'Female', 1, 0 )) as FemaleCnt,
      count(*) AllTeamMembers
  from
      team_member tm
  group by
      tm.Team_ID
  having
         AgeInRange = AllTeamMembers
     AND MaleCnt > 0
     AND FemaleCnt > 0
于 2012-06-04T10:47:52.330 回答
0

类似于 - SELECT * FROM t1 WHERE key_col > 1 AND key_col < 10;

检查这个例子 - http://www.roseindia.net/sql/mysql-example/mysql-range.shtml。希望能帮助到你!

于 2012-06-04T03:05:16.377 回答
0

你可以这样做:
1. SELECT * FROM T2 WHERE Gender='Male' and Age BETWEEN 18 AND 25.
2 SELECT * FROM T2 WHERE Age BETWEEN 18 AND 25..
希望能帮助到你!

于 2012-06-04T03:20:03.843 回答
0

BTW team_member_id 必须是唯一的,否则此列无用!

所有男性和女性团队的列表,其中任一性别在 18 至 25 岁之间。

SELECT * FROM team_member WHERE Age BETWEEN 18 AND 25 GROUP BY team_id.

结果

| team_member_id | team_id | age | gender |
===========================================
| 1              | 1       | 20  | Male   |
-------------------------------------------
| 1              | 2       | 25  | Male   |
-------------------------------------------
于 2012-06-04T04:26:19.287 回答