我有3张桌子:
地址
id, address, city, zipcode
人(1500条记录)
id, address_id, firtname, lastname, sex, title
建筑物(100条记录)
id, address_id, name, type_of_building
多人/建筑物共用同一地址。我需要列出所有地址及其人员或建筑信息。所以,我的查询应该返回总共1600条记录。
我需要编写哪种查询来检索此信息?
答案 0 :(得分:3)
由于您需要来自两个不同数据集的所有记录,因此您需要使用INNER JOIN
和UNION
。这样的事情可能有用:
SELECT p.id, p.firstname, p.lastname, p.sex, p.title, a.address, a.city, a.zipcode
FROM persons p
INNER JOIN addresses a on a.id = p.address_id
UNION ALL
SELECT b.id, b.name, '', '', b.type_of_building, a.address, a.city, a.zipcode
FROM buildings b
INNER JOIN addresses a on a.id = b.address_id
答案 1 :(得分:0)
这将是 UNION ,因为您要合并两个不同数据集的结果。为了获得统一信息,您需要使用相同的字段,因此我将使用示例:
(SELECT address_id, firstname AS value1, lastname AS value2, sex AS value3, title AS value4 FROM persons)
UNION
(SELECT address_id, name AS value1, type_of_building AS value2, 0 AS value3, 0 AS value4 FROM buildings)