mysql计数相关表

时间:2014-01-23 16:26:09

标签: mysql join count

大家好我想计算一些条目,但我不知道是否可以用连接来做。情况是

我有一张桌子

student_profile

Id | Name
---------
1  | Name1
2  | Name2 
3  | Name3 

student_application 其中profile_id与student_profile.id相关

     Id | profile_id | Data
     ----------------------
     1      2          data1
     2      2          data2
     3      2          data3

student_holiday

Id | app_id | date
-----------------------
1      2      2014-01-01
2      3      2014-02-02

所以我的所有student_application都是

Select sa.id, s.name From student_application sa 
INNER JOIN student_profile s ON s.id =  sa.profile_id

我想算一下学生有多少假期,但我在student_holiday表中没有profile_id。我有app_id,所以我不能做左连接student_holiday sh on sh.app_id = sa.id,这不会给出正确的数字。

此处sqlfiddle

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

SELECT student_profile.ID, student_profile.Name, student_holiday.ID
FROM (student_profile INNER JOIN student_holiday ON student_profile.ID = student_holiday.ID) INNER JOIN student_application ON student_holiday.ID = student_application.ID;

你去吧!!!按照上面的说明匹配所有表中的ID,这是获得假期的关键。

或者与profile_id匹配

**SELECT student_profile.ID, student_profile.Name, student_holiday.ID
FROM (student_profile INNER JOIN student_holiday ON student_profile.ID = student_holiday.ID) INNER JOIN student_application ON Trim(student_holiday.ID) = 
student_application.profile_id;**

答案 1 :(得分:0)

以下是加入第3张表的数据:

Select s.name, sa.some_data as application_data,h.some_data as holiday_data 
From student_application sa
INNER JOIN student_profile s ON s.id = sa.profile_id
INNER JOIN student_holiday h  ON h.app_id = sa.id;

请注意,这只会返回具有相关假日的应用程序的记录。

然后计算它们,我们只是:

Select s.name, sa.some_data as application_data,count(h.some_data) as holiday_data 
From student_application sa
INNER JOIN student_profile s ON s.id = sa.profile_id
INNER JOIN student_holiday h  ON h.app_id = sa.id
GROUP BY s.name

请注意,此答案基于您在sqlfiddle中使用的字段名称(Data = some_data and date = some_data)