我想从两个表中得到结果:
表A
create table A
( propertyId int not null
,PRIMARY KEY (propertyId))
表B
create table B
( Id int not null
, propertyId int
, FOREIGN KEY (propertyId ) REFERENCES A(propertyId))
现在我希望Table A
中存在Table B
的结果总计数ID以及Table B
中不存在的总计数ID
SELECT COUNT(property.propertyId) AS 'Occupied'
,(
SELECT COUNT(property.propertyId)
FROM property
INNER JOIN agreement ON property.`propertyId` <> agreement.`propertyId`
) AS 'Vacant'
FROM property
INNER JOIN agreement ON property.`propertyId` = agreement.`propertyId`
WHERE agreement.`isActive` = '1'
答案 0 :(得分:1)
您可以Left join
来获得正确的结果。
select
sum (
case when a.propertyId is not null then 1
else 0
end
) as present_cnt,
sum (
case when a.propertyId is null then 1
else 0
end
) as not_present_cnt
from property p
left join agreement a on p.propertyId = a.propertyId
where a.isActive = '1';
left join
将从与a.propertyId
对应的agreement
获取p.propertyId
的数据,如果找不到匹配项,则null
答案 1 :(得分:0)
您的解决方案应该基于这一原则,也可以在this SQLFiddle中举例说明:
SELECT count(CASE
WHEN propertyID IS NOT NULL
AND fk_propertyID IS NOT NULL
THEN 1
ELSE NULL
END) 'exist_in_both_tables'
,count(CASE
WHEN propertyID IS NOT NULL
AND fk_propertyID IS NULL
THEN 1
ELSE NULL
END) 'does_not_exist_in_b'
FROM (
SELECT *
FROM tablea a
LEFT JOIN tableb b ON a.propertyID = b.fk_propertyID
UNION
SELECT *
FROM tablea a
RIGHT JOIN tableb b ON a.propertyID = b.fk_propertyID
) result
您需要复制查询并同时使用LEFT
和RIGHT
个联接以及UNION
这两个单独查询的结果来模拟FULL JOIN
的结果。< / p>
在模拟之后,您需要再次检查此结果集,方法是将其作为子查询,然后使用聚合函数COUNT()
和CASE
语句来计算您匹配的数量在两个表中都有。
因此,您的最终查询应如下所示:
SELECT count(CASE
WHEN Property_PropertyID IS NOT NULL
AND Agreement_PropertyID IS NOT NULL
THEN 1
ELSE NULL
END) 'Occupied'
,count(CASE
WHEN Property_PropertyID IS NOT NULL
AND Agreement_PropertyID IS NULL
THEN 1
ELSE NULL
END) 'Vacant'
FROM (
SELECT property.propertyID 'Property_PropertyID'
FROM property
LEFT JOIN agreement ON property.`propertyId` = agreement.`propertyId`
WHERE agreement.`isActive` = '1'
UNION
SELECT agreement.propertyID 'Agreement_PropertyID'
FROM property
RIGHT JOIN agreement ON property.`propertyId` = agreement.`propertyId`
WHERE agreement.`isActive` = '1'
) ResultSet