MySQL两个表两列COUNT

时间:2013-05-09 15:24:30

标签: mysql

我有两张桌子

  

TEAMS - team_id和team_name(以及其他内容)
  SCHEDULE - game_id,team_a,team_b,team_a_id,team_a_id(以及其他内容)

我正在尝试创建一个结果,其中我发现team_name(或team_id)在team_ateam_b列中显示的次数(或{ {1}}或team_a_id

TEAMS
team_id team_name
1001纽约
克利夫兰1011年 1021年底特律 1031休斯敦

SCHEDULE
game_id team_a team_b team_a_id team_b_id
1纽约克利夫兰1001 1011
2纽约底特律1001 1021
3 Cleveland Houston 1011 1031

答案: 纽约2 克利夫兰2 底特律1 休斯顿1

4 个答案:

答案 0 :(得分:2)

单程

Select t.team_name,Sum(allteams.teamcount) as NumberOfTimes
From teams t
inner join(
select team_a_id as team_ID, 1 as teamcount From Schedule
Union 
Select team_b_id, 1 From Schedule
) allteams
on allteams.Team_ID = t.Team_ID
Group By t.team_name

答案 1 :(得分:1)

也许

SELECT count(*)
FROM teams
WHERE $teamID IN (team_a, team_b)

答案 2 :(得分:0)

看起来很简单,除非我遗漏了什么。只需选择一个计数,然后使用WHERE OR clause

SELECT COUNT(*)
FROM schedule
WHERE team_a = 'Team Name'
OR team_b = 'Team Name'

可替换地:

WHERE team_a_id = 'Team ID'
OR team_b_id = 'Team ID'

答案 3 :(得分:0)

尝试这样的事情:

select count(*)
from teams t
join schedule s on (s.team_a = t.team_name OR s.team_b = t.team_name)