0

Let's say that I have a table called Appointments, another called Clients and a joining table called ClientsAppointments which relates the two aforementioned ones. This is used in a scenario where a client can have several appointments, and several clients can attend to the same appointment (n-n relation).

I would like to list the Appointments with a field "clients" being an array of all the Clients related to that appointment. What I've tried so far:

    SELECT * FROM Appointments a
    INNER JOIN ClientsAppointments ca ON ca.IdAppointment = a.IdAppointment
    INNER JOIN Clients c ON c.IdClient = ca.IdClient

That doesn't work, of course. It gives me a list of appointments repeated with each of the clients they have. Then in PHP I would process them to achieve this. It seemed more efficient this way rather than making multiple queries because there's usually only one client per appointment.

Table schema (these are not the actual tables, but simplified to illustrate the case):

    Appointment(
            INT idAppointment,
            DATETIME start,
            DATETIME end)

    Clients(
            INT idClient,
            VARCHAR name)

    ClientsAppointments(
            INT idAppointment,
            INT idClient)
4

2 に答える 2

0

MySQL をデータベースとして使用する場合は、GROUP_CONCAT を使用してみてください。

SELECT a.IdAppointment,GROUP_CONCAT(CAST(ca.IdClient AS CHAR) SEPARATOR ',')  FROM Appointments a
INNER JOIN ClientsAppointments ca ON ca.IdAppointment = a.IdAppointment
group by a.IdAppointment
于 2012-08-08T07:42:16.650 に答える
0

使ってみてLEFT OUTER JOIN

SELECT a.*,c.Name FROM ClientsAppointments ca
LEFT OUTER JOIN Appointments a ON ca.IdAppointment = a.IdAppointment
LEFT OUTER JOIN Clients c ON ca.IdClient = c.IdClient
于 2012-08-08T07:18:48.820 に答える