多表sqlite的连接查询问题

Issue in join query of multiple tables sqlite

朋友们好,我有如下四张表

property_master --> "p_id" , "p_name" , "p_address" , "p_city" , "p_state" ,"r_id"

property_unit -->"unit_id"   , "p_id"  , "unit_name"   ,"r_id"

unit_info -->    "unit_info_id"   ,"unit_id" INTEGER,"p_id"   ,"p_bathroom"  ,"p_bedroom"  ,"p_size"  ,"p_rent"  ,"p_isrent"  ,"u_note" ,"r_id" 

tanant_master -->  "t_id"   , "t_name"  ,"t_cell_no"  ,"t_phone_no"  ,"t_mail"  ,"t_deposit"   ,"r_id"

property_assign-->  "t_assign_id"   , "unit_info_id"  ,  "t_id"  , "t_start_date"  , "t_end_date"  , "  t_rent_due_day"  , "t_lease_alert"  , "t_status"  ,"r_id"

我的查询如下

Select p_name As "Property",
p_id AS "PID",
(Select Count(unit_id) from property_unit where   property_master.p_id=property_unit.p_id )As "UnitCount",
(Select Count(unit_info_id) from unit_info where unit_info.unit_info_id=property_assign.unit_info_id )As "TenantCount"
From property_master  ,property_assign Group by property_master.p_id

我需要总租户数 属性wise 但是当我 运行 上面的查询它只给我第一个 属性 租户数所有 属性 知道我怎么能解决了吗?

尝试这样的事情:

select a.PID,
       MAX(a.Property) as "Property",
       COUNT(a.unit_id) as "UnitCount",
       SUM(a.TenantCount) as "TenantCount"
  from (
        select property_master.p_id as "PID",
               MAX(property_master.p_name) as  "Property",
               property_unit.unit_id,
               COUNT(property_assign.t_id) as "TenantCount"
          from property_master
          JOIN property_unit ON property_master.p_id = property_unit.p_id
          JOIN unit_info ON unit_info.unit_id = property_unit.unit_id
          JOIN property_assign ON unit_info.unit_info_id = property_assign.unit_info_id 
         group by property_master.p_id, property_unit.unit_id
       ) a,
 group by a.PID

注意 1 您可能需要使用 LEFT OUTER JOIN 而不是 JOIN 取决于您的数据结构(可以 property_assign 为空或不?)

注2.抱歉,我没法测试。你应该自己做。