how to use sql join in mysql

前端 未结 4 1117
礼貌的吻别
礼貌的吻别 2021-01-23 07:33

table name: tbl_schedule

tr_id(P.K.)  mr_id(F.K.)   sch_date   doctor_id   
-----------  -----------   --------   ----------
1              23         01/01/2012         


        
4条回答
  •  长发绾君心
    2021-01-23 08:20

        select tu.mr_fname, tu.mr_lname, count(ts.mr_id) as `count` 
    from tbl_user tu 
    inner join tbl_schedule ts on ts.mr_id = tu.mr_id and 
          ts.sch_date between '2012-01-01' and '2012-08-01' 
    group by tu.mr_id
    

    The above will get you all the users with a row in the schedule it. So the users with a count of 0 will not show up.

    select tu.mr_fname, tu.mr_lname, count(ts.mr_id) as `count` 
    from tbl_user tu 
    left join tbl_schedule ts on ts.mr_id = tu.mr_id and 
          ts.sch_date between '2012-01-01' and '2012-08-01' 
    group by tu.mr_id
    

    This query will select the first name and last name of the user and count the number of times that user id appears in the schedule table.

    It does this by grouping by the user id.

    And additionally it uses a left join based on user id and date. It is important to put the date condition here so that all users are selected. This is because the left join will include all users that did not match too. But if you put this on the where clause, all users would not be selected. In other words, you will not get a count of zero for 'gerry chandan' if you put the date condition in the where clause. Instead he would be left off the results.

提交回复
热议问题