0

您使用哪个联接从父表和子表中选择数据,其中父表可能不包含子数据?

4

3 回答 3

1

我认为您的问题更恰当地表述为:

如何在主表中查找子表中没有任何项目的项目?

这是 SQL 中一个非常常见的问题,并且有一个已知的解决方案......这在 T-SQL 中有效(你需要总是说出你在使用什么)

select m.master_data, c.child_data
from master_table m
left outer join child_table c 
    on m.ID = c.ID
where c.child_data IS NULL

当子表中没有任何内容时,OUTER 连接会在子表列中产生空值,因此您只需在子表中显示具有空值的行即可。您不会在结果中显示子表中的任何列。

于 2013-04-26T21:41:00.327 回答
1

有几种方法可以找到没有租约的房产。

  1. 在 where 子句中使用子查询

    select *
    from propertys
    where propertys.propertyID not in (select propertyID from lease);
    
  2. 或者,您可以在 where 子句中使用带有空检查的左连接

    select *
    from propertys
    left join lease on lease.propertyID = propertys.propertysID
    where lease.leaseID is null;
    
于 2013-04-26T21:43:19.223 回答
0
SELECT 
p.* 
FROM
Property p
LEFT JOIN Lease l ON p.propertyid = l.propertyid
WHERE l.propertyid IS NULL
于 2013-04-26T21:40:16.033 回答