我有两张桌子。在这些表中,我的停止ID可能位于其中一个或两个中。如果我的停止ID在B中不存在,它应该从A中选择。如果它在A中不存在,它应该从B中选择。如果两个表中都存在停止ID,那么我想优先考虑B并从中检索行B.下面的查询总是返回B中的值。你可以帮我解决这个问题吗?
String selectQuery = "SELECT "
+ stop_id + ","
+ name + ","
+ latitude + ","
+ longitude + ","
+"1 as "+priority
+" FROM "+ A
+" UNION SELECT "
+ stop_id + ","
+ name + ","
+ latitude + ","
+ longitude + ","
+"2 as "+priority
+" FROM "+ B
+" WHERE " + stop_id + " =? "
+" ORDER BY "+priority
+" LIMIT 1 ";
Cursor cursor = db.rawQuery(selectQuery, new String[] {id});
答案 0 :(得分:1)
在UNION ALL
中,您应该将WHERE
条款应用于SELECT
个;您当前的代码仅将条件应用于B
侧,而A
侧则返回所有行。最后LIMIT 1
隐藏了这个问题。
字符串连接不容易看到,但是您应该两次传递id
,并在查询中使用两个?
占位符:
SELECT stop_id, name, latitude, longitude, 1 as priority
FROM A
WHERE stop_id = ?
UNION ALL
SELECT stop_id, name, latitude, longitude, 2 as priority
FROM B
WHERE stop_id = ?
ORDER BY priority DESC
LIMIT 1