我有以下3个表(组织,组织地址,地址)。每个组织都有多个地址,其中一个是主要的。如果组织有主要地址,我需要选择主要地址,否则该列可以为null或空白。
如何在mysql中编写sql子查询? 请帮帮我,
谢谢,
答案 0 :(得分:3)
您只需LEFT JOIN
select a.orgid, b.orgaddressid, c.address
from organization a
left join organization_address b on a.orgid = b.orgid and b.isprimaryaddress = 'YES'
left join address c on b.orgaddressid = c.addressid
where a.orgid = 1;
答案 1 :(得分:2)
也许是这样的。我认为您需要对两个表使用LEFT JOIN
:
select
organization.orgid,
organization_address.orgaddressid,
address.address
from
organization
LEFT JOIN organization_address
ON organization_address.orgid = organization.orgid
AND organization_address.isprimaryaddress = 'YES'
LEFT JOIN address
ON organization_address.orgaddressid = address.addressid;
答案 2 :(得分:0)
如果右表中存在匹配的行,则LEFT JOIN选择左表中的行并匹配右表中的行。如果右表中没有任何匹配的行,则查询将为右表中的列返回NULL。
SELECT o.OrgId, oa.OrgaddressId, a.Address FROM Organization AS o
LEFT JOIN 'Organization Address' AS oa ON oa.OrgId=o.OrgId
LEFT JOIN Address AS a ON a.AddressId=oa.OrgAddressId
WHERE oa.IsPrimaryId='YES';
答案 3 :(得分:0)
子查询比连接查询慢,所以我只是告诉你,请忽略子查询
如果您想获得此类结果,可以使用左连接
select a.orgid, b.orgaddressid, c.address
from organization a
left join organization_address b on a.orgid = b.orgid and b.isprimaryaddress = 'YES'
left join address c on b.orgaddressid = c.addressid
where a.orgid = 1;
左连接意味着
返回左表(table1)中的所有行,右表(table2)中的匹配行。当没有匹配时,右侧的结果为NULL。
访问Google中的加入类型,您可以获得更多想法