对其他表上的Count(*)相关行的语句

时间:2013-08-06 05:37:27

标签: php mysql sql database

我有两张名为patient_listdentist_list的桌子,牙医在这里可以有很多病人,我想知道牙医有多少病人订购。

我这里有一个示例代码,我得到每位患者的医生:

$query_dentist = "SELECT * FROM dentist_list ORDER BY ID ASC";
$res_dentist   = mysql_query($query_dentist);

if ($res_dentist) {
    while ($row_dentist = mysql_fetch_array($res_dentist)) {

    }
}

在我找到所有的牙医之后,我会在一段时间内创建一个新的查询,我会得到所有患者的数量。

$dentist_id = $row_dentist['id'];
$query_patient= "SELECT COUNT(*) as patient_num FROM patient_list
                                 WHERE dentist_id ='$dentist_id'";

$res_patient=mysql_query($query_patient);
if($res_patient)
{
     while($row_patient=mysql_fetch_array($res_patient))
     {

     }
 }

例如,查询的输出是:

doctor 1 has 10 patient
doctor 2 has 5 patient
doctor 3 has 100 patient

而不是使用PHP,是否可以使用MySQL语句?我将只创建一个查询,因为我需要它按患者数量排序。

2 个答案:

答案 0 :(得分:0)

SELECT COUNT(*) AS Patient_Num FROM patient_list GROUP BY dentist_id ORDER BY 1

答案 1 :(得分:0)

您可以尝试使用此代码:

  select d.Name, -- <- put dentist information here
         (select count(1) from patient_list p where p.dentist_id = d.dentist_id) 
    from dentist_list d
order by 2 asc -- <- order by by the 2nd field that is (select count(1...