假设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 |
-------------------------------------------
我如何搜索这样的内容:
我基本上正在寻找有关如何在team
的所有子记录中应用某些过滤器(例如年龄)的一般策略。建议?
答案 0 :(得分: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
答案 1 :(得分:0)
像 - SELECT * FROM t1 WHERE key_col> 1 AND key_col< 10;
检查此示例 - http://www.roseindia.net/sql/mysql-example/mysql-range.shtml。希望它有所帮助!
答案 2 :(得分:0)
您可以按以下方式执行:
1. SELECT * FROM T2 WHERE Gender='Male' and Age BETWEEN 18 AND 25
。
2. SELECT * FROM T2 WHERE Age BETWEEN 18 AND 25
。
希望它有所帮助!
答案 3 :(得分: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 |
-------------------------------------------