连接查询多个表sqlite的问题

时间:2015-03-05 09:23:35

标签: android mysql sqlite left-join

你好朋友我有四张桌子如下

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

我需要物业总租户数,但当我在查询上方运行时,它只给我所有物业的第一个物业租户计数,我知道如何解决它?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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。抱歉,我无法测试。你应该自己做。