SQL,获得与id的区别

时间:2015-08-06 10:55:21

标签: mysql sql

我想从两个表中得到结果:

表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'

2 个答案:

答案 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

您需要复制查询并同时使用LEFTRIGHT个联接以及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