MySQL从一个表中连接多个行,而从其他表中只选择一行

时间:2012-11-12 11:31:45

标签: mysql

也许有点奇怪的标题描述,但我基本上想要实现GROUP_CONCAT()函数所做的事情,然后才保留双重条目。

我想要加入四个表,clientdoctorphysiorecords

根据变量$client我想获取客户详细信息,参加医生和治疗师(三个表中的一行)并加入该用户的所有记录。

在这种情况下说$client = 1records表有五列记录,其中列r_client_id = 1。如果我运行如下的查询,我只从records表中获得一条记录,即第一次出现r_client_id = 1(理所当然):


SELECT
    client.c_id, client.c_name
    doctor.d_name, 
    physio.p_name, 
    records.r_record
FROM
    adm_clients AS client

    INNER JOIN 
        norm_client_doctor AS ncd ON ncd.ncd_client_id = client.c_id
    INNER JOIN 
        adm_doctor AS doctor ON doctor.d_id = ncd.ncd_doctor_id
    INNER JOIN 
        norm_client_physio AS ncp ON ncp.ncp_client_id = client.c_id
    INNER JOIN 
        adm_physio AS physio ON physio.p_id = ncp.ncp_physio_id

        LEFT JOIN 
            adm_doctor_records AS records ON records.r_client_id = client.c_id
WHERE
    client.c_id = '".$client."'

现在假设r_client_id = 1就是这样的五条记录:


+------+-------------+-------------------+----------+
| r_id | r_client_id | r_record          | r_date   |
+------+-------------+-------------------+----------+
| 1    | 1           | regular visit     | 10/10/12 |
+------+-------------+-------------------+----------+
| 3    | 1           | emergency control | 24/10/12 |
+------+-------------+-------------------+----------+
| 7    | 1           | regular visit     | 08/09/12 |
+------+-------------+-------------------+----------+
| 18   | 1           | delivery          | 03/01/12 |
+------+-------------+-------------------+----------+
| 20   | 1           | health checkup    | 10/12/11 |
+------+-------------+-------------------+----------+

我希望我的输出是这样的数组:


Client 1
 - Name Doctor
 - Name Physio

Records
 - Emergency control, 24/10/12
 - Regular visit, 10/10/12
 - Regular visit, 08/09/12
 - Delivery, 03/01/12
 - Health checkup, 10/12/11

我可以成像的最接近的一个是在记录上添加GROUP_CONCAT(),但当然,这会将“常规访问”分组,所以我会得到4行而不是5行


    GROUP_CONCAT(DISTINCT records.r_record SEPARATOR '|')
[..]
    echo(str_replace("|","<br>",$show->r_record));

有人知道如何显示所有匹配的记录吗?我感觉我很亲近,但我现在没有选择..

修改 我忘了提到当我删除DISTINCT时,它会显示所有记录两次..

解决:

让它像这样工作:


    GROUP_CONCAT(DISTINCT 
        CONCAT (records.r_date, '~', records.r_record, '~', records.r_paraph)
    SEPARATOR '|') AS clientDoctorRecords, 

1 个答案:

答案 0 :(得分:2)

尝试:

SELECT
    client.c_id, client.c_name
    doctor.d_name, 
    physio.p_name, 
    GROUP_CONCAT(records.r_record)
FROM
    adm_clients AS client

    INNER JOIN 
        norm_client_doctor AS ncd ON ncd.ncd_client_id = client.c_id
    INNER JOIN 
        adm_doctor AS doctor ON doctor.d_id = ncd.ncd_doctor_id
    INNER JOIN 
        norm_client_physio AS ncp ON ncp.ncp_client_id = client.c_id
    INNER JOIN 
        adm_physio AS physio ON physio.p_id = ncp.ncp_physio_id

        LEFT JOIN 
            adm_doctor_records AS records ON records.r_client_id = client.c_id
WHERE
    client.c_id = '".$client."'
GROUP BY
    client.c_id

如果您希望r_date在一列中显示record,那么您可以先使用普通CONCAT,然后再使用GROUP_CONCAT