如何在Sqlite中优先考虑一个表

时间:2015-04-04 11:15:54

标签: java sqlite union

我有两张桌子。在这些表中,我的停止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});

1 个答案:

答案 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