[英]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. 我需要的是一个SQL查询(对于mysql 5.1.54数据库),最终将给我一个PHP数组,其中包含来自多个表的信息。 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. 我可以通过仅对前3个表进行查询,然后在foreach循环中在表4和5中添加信息来完成此操作。
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. 但是,我需要使用查询进行搜索/过滤(例如:在伙伴ID为9的地方显示所有保留),因此我需要SQL来选择相应的保留。
A simplified version of the database: 数据库的简化版本:
Table 1: reservations: 表1:保留:
id id_client id_tour
1 22 6
2 23 5
Table 2: clients (one reservation has one client): 表2:客户(一个预订有一个客户):
id name
22 John
23 William
Table 3: tours (one reservation has one tour) 表3:旅行(一项预订有一项旅行)
id name
5 big tour
6 small tour
Table 4: partners (one reservation can have multiple partners): 表4:合作伙伴(一个预订可以有多个合作伙伴):
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): 表5:指南(一个预订可以有多个指南):
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. 我使用GROUP_CONCAT获取多个合作伙伴和指南ID。 Biggest problem I have is not being able to include the reservations that have no partners and/or guides like reservation 2. 我遇到的最大问题是无法包含没有合作伙伴和/或指南的预订,例如预订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: 要包括没有合作伙伴和指南的所有预订,您需要使用OUTER JOINs
,例如,以下查询将为您提供表4,表5中的所有信息,包括您的条件:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.