简体   繁体   中英

SQL query for multiple (one-to-many) tables in mysql database

I have a database with tours (group city tours with guide). What I need is a SQL query (for a mysql 5.1.54 database) that will eventually give me a PHP array with the information out of multiple tables combined. I'm able to accomplish this by doing a query just for the first 3 tables and then adding the information in table 4 and 5 within a foreach loop.

But, I need to use the query for searching/filtering (like: show all reservations where partner has id 9) so I need SQL to select the corresponding reservations.

  1. Reservations with no partners (table 4) and/or guides (table 5) must be included.
  2. All partners and guides must be included in the result (reservation can have more partners/guides)
  3. All information in table 4 and 5 must be included (like the status from table 4).

A simplified version of the database:

Table 1: reservations:

id    id_client    id_tour
1     22            6
2     23            5

Table 2: clients (one reservation has one client):

id    name
22    John
23    William

Table 3: tours (one reservation has one tour)

id    name
5     big tour
6     small tour    

Table 4: partners (one reservation can have multiple partners):

id    id_reservation    id_partner_type    id_partner    status
34    1                 9                  16            1
35    1                 9                  17            0

Table 5: guides (one reservation can have multiple guides):

id    id_reservation    id_guide
18    1                 14
19    1                 15

I have tried to work this out but I just can not get a query that does the job. I used GROUP_CONCAT to get the multiple partner and guide id's. Biggest problem I have is not being able to include the reservations that have no partners and/or guides like reservation 2.

To include all reservations that have no partners and guides you need to use OUTER JOINs , for example the following query will gives you all information from your tables 4, 5 including your condition:

Select p.*, g.*
from reservations r  
left outer join partners p on p.id_reservation = r.id
left outer join guides g on g.id_reservation = r.id
where p.id_reservation is null and g.id_reservation is null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM