将UNION ALL与其他表一起使用时,保留一个表中的所有记录

时间:2014-06-30 14:24:51

标签: android sql sqlite union-all

我的两张表 - UserLogUserInspectionUserLog UNION ALL UserInspection

我希望保留UserLog的所有记录,但希望保留UserInspection值{em>与 OWNER值相同的column owner的记录

插图:

String OWNER = "0394850935803";

ArrayList<HashMap<String, String>> list = 
         new ArrayList<HashMap<String,String>>();

HashMap<String, String> dataMap = null;

table_log = "SELECT Type_Log, Start AS SortDate, Location, 
             Remark, Odometer, NULL AS Start_odo, NULL AS owner 
             FROM UserLog WHERE deleted !=1 ";

table_insp = "select Type, Date, Location, Observation, NULL, 
              Start_odo, owner from UserInspection where deleted !=1 ";

final_query = table_log + " UNION ALL " + table_insp + " ORDER BY SortDate";

cur = dbAdapter.rawQuery(final_query, null);

cur.moveToFirst();

for (int j = 0; j < cur.getCount(); j++)
{
    /*Keep all the UserLog records but keep only*/
    /*those UserInspection records whose owner column value*/
    /*from cursor matches the OWNER String value*/
    if((cur.isNull(cur.getColumnIndex("owner"))) 
     || OWNER.equals(cur.getString(cur.getColumnIndex("owner")))){

      /*Code to get other column values*/
      dataMap = new HashMap<String, String>();
      dataMap.put("Location", location);
      list.add(dataMap);
    }
}

但即使ArrayList list表有一些记录,我在 UserLog 中也什么也得不到。

2 个答案:

答案 0 :(得分:1)

如果您可以将第二个表的内容作为附加列处理,那么请使用left outer join

select *
from (SELECT Type_Log, Start AS SortDate, Location, 
             Remark, Odometer, NULL AS Start_odo, NULL AS owner 
      FROM UserLog
      WHERE deleted <> 1
     ) table_log left outer join
     (select Type, Date, Location, Observation, NULL, 
             Start_odo, owner
      from UserInspection
      where deleted <> 1 
     ) table_insp
     on table_log.owner = table_insp.owner;

如果您真的想要单独的行,可以使用with

with table_log as 
      SELECT Type_Log, Start AS SortDate, Location, 
             Remark, Odometer, NULL AS Start_odo, NULL AS owner 
      FROM UserLog
      WHERE deleted <> 1
    ),
     table_insp as (
      select Type, Date, Location, Observation, NULL, 
              Start_odo, owner
      from UserInspection ui
      where deleted <> 1 and
            exists (select 1 from table_log where ui.owner = table_log.owner)
     )
select *
from table_log
union all
select *
from table_insp;

答案 1 :(得分:1)

只需将附加条件放入WHERE子句中,然后您就不需要在代码中检查它了:

...
table_insp = "select Type, Date, Location, Observation, NULL, "+
             "Start_odo, owner from UserInspection "+
             "WHERE deleted !=1 "+
               "AND owner = ?";

final_query = table_log + " UNION ALL " + table_insp + " ORDER BY SortDate";
String[] parameters = new String[] { OWNER };

cur = dbAdapter.rawQuery(final_query, parameters);
...