MySQL三表查询

时间:2015-04-10 17:55:40

标签: mysql database

我在获取此查询以获取我正在寻找的数据时遇到了一些麻烦。

我有三张桌子 -

guest_list_parties

guest_list_guests

guests

SELECT guest_list_parties.note, guests.accepted, guest_list_guests.first_name, guest_list_guests.last_name, guest_list_guests.title, guest_list_parties.note
FROM guest_list_guests
INNER JOIN guest_list_parties ON guest_list_guests.party_id = guest_list_parties.id
INNER JOIN guests ON guests.guest_list_guest_id = guest_list_guests.id

此处的查询仅返回“访客”中有条目的记录。表。

我想返回所有记录,无论“访客”中是否有链接条目。表。

话虽如此,我会使用左外连接还是右外连接?

1 个答案:

答案 0 :(得分:1)

请改用left join,但这会检查guest_list_parties上的数据是否可用,因为该inner join表格中的数据。

SELECT guest_list_parties.note, 
guests.accepted, 
guest_list_guests.first_name, 
guest_list_guests.last_name,
guest_list_guests.title, guest_list_parties.note
FROM guest_list_guests
INNER JOIN guest_list_parties 
ON guest_list_guests.party_id = guest_list_parties.id
LEFT JOIN guests ON guests.guest_list_guest_id = guest_list_guests.id