我几乎在那里,但没有完全返回我需要的结果。
我有3张桌子。 program_location,hcp_data,guest_data,都有正确的主键。
hcp_data中的每一行都包含一个引用(通过外键)到1个程序位置。 guest_data中的每一行都包含对hcp_data中一行的引用。可能有多个guest虚拟机绑定到一个hcp_data条目。将这些表格视为聚会地点,被邀请者以及受邀者选择将他们带到同一地点的人员。因此,通过他们的关系,我可以通过他们链接到的hcp的位置来确定访客的位置。
所以我要做的是从hcp_data和additional_guest表中选择所有行,并从program_locations表中连接几行。本质上,目的是转储数据,使其作为单个平面文件有意义。
这就是我所拥有的:
SELECT lname, fname, degree, email, job_title, office_addr_line_1, office_addr_line_2, hcp_data.city, hcp_data.state, hcp_data.zip, phone, timestamp, program_location.restaurant_name, program_location.city AS restaurant_city, program_location.state AS restaurant_state
FROM hcp_data
LEFT JOIN program_location
ON hcp_data.program_location_idprogram_location = program_location.idprogram_location
UNION
SELECT lname, fname, degree, email, job_title, office_addr_line_1, office_addr_line_2, additional_guest.city, additional_guest.state, additional_guest.zip, phone, timestamp, program_location.restaurant_name, program_location.city AS restaurant_city, program_location.state AS restaurant_state
FROM additional_guest
LEFT JOIN program_location
ON
目前最后一个ON是空白的。我相信这是我被困的地方。我想我需要为其中一方做复合选择,但我不确定。
请帮忙!谢谢!
编辑,BTW,每个表的主键只是前面附加“id”的表名,即“idprogram_location” 外键是它们来自的表,下划线,它们来自的表中列的名称:即“program_location_idprogram_location”
答案 0 :(得分:0)
所以我已经弄清楚了。如果有更简单或更好的方式(我不怀疑),请分享!
SELECT lname, fname, degree, email, job_title, office_addr_line_1, office_addr_line_2, hcp_data.city, hcp_data.state, hcp_data.zip, phone, timestamp, program_location.restaurant_name, program_location.city AS restaurant_city, program_location.state AS restaurant_state
FROM hcp_data
LEFT JOIN program_location
ON program_location.idprogram_location = hcp_data.program_location_idprogram_location
UNION
SELECT lname, fname, degree, email, job_title, office_addr_line_1, office_addr_line_2, additional_guest.city, additional_guest.state, additional_guest.zip, phone, timestamp, program_location.restaurant_name, program_location.city AS restaurant_city, program_location.state AS restaurant_state
FROM additional_guest
LEFT JOIN program_location
ON program_location.idprogram_location =
(SELECT idprogram_location
FROM program_location
WHERE idprogram_location =
(SELECT program_location_idprogram_location
FROM hcp_data
WHERE idhcp_data =
(SELECT hcp_data_idhcp_data
FROM additional_guest LIMIT 1)));