我的两张表 - UserLog
和UserInspection
,UserLog 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
中也什么也得不到。
答案 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);
...