尝试根据条件进行查询

时间:2019-05-24 23:56:31

标签: sql sqlite android-sqlite

我在这里阅读了大多数类似问题的解决方案,但是并不能解决我的问题,也找不到任何可以帮助我的在线方法。

我正在尝试在user_id = session user_id的情况下进行查询,但在我做出INNER join时却报错

  

列名不明确

为此

public List<CartModelClass>getCarts1(){

    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String[] sqlSelect = { "ID" , "user_id", "food_id", "quantity", "price", "origin", "destination","description","company_name","search_id"};

    String sqltable2 = "OrderDetails LEFT JOIN OrderDetails WHERE user_id LIKE '%%' ";

    qb.setTables(sqltable2);
    Cursor c = qb.query(db,sqlSelect, null, null ,null ,null ,null);

    final List<CartModelClass> result = new ArrayList<>();
    if (c.moveToFirst()) {
        do {
            result.add(new CartModelClass(
                    c.getString(c.getColumnIndex("user_id")),
                    c.getString(c.getColumnIndex("food_id")),
                    c.getString(c.getColumnIndex("quantity")),
                    c.getString(c.getColumnIndex("price")),
                    c.getString(c.getColumnIndex("origin")),
                    c.getString(c.getColumnIndex("destination")),
                    c.getString(c.getColumnIndex("description")),
                    c.getString(c.getColumnIndex("company_name")),
                    c.getString(c.getColumnIndex("search_id"))
            ));
        } while (c.moveToNext());
    }
    return result;
}

所以我更改了InnerJoin并将其设置为表where user_id like"%%",但我只得到添加到购物车中的最后一个user_id并显示所有用户的所有数据

我只想显示为user_id = session user_id添加的购物车,所以我可以在这里使用它

loadListFood

private void loadListFood(){


sessionManager= new SessionManager(getActivity());
final Hashmap<String, String> user = sessionManager.getUserDetail();
user.get(USER_ID);

listdata = new Database(this.getContext.getCarts1());
for(CartModelClass order : listdata)
user_id = order.getUser_id


if(user.get(USER_ID).equals(user_id)){
listdata = new Database(this.getContext()).getCarts();


        adapter = new CartAdapter(listdata, this.getContext());
        recyclerView.setAdapter(adapter);


        int total = 0;
        for (CartModelClass order : listdata) {


            total += (Integer.parseInt(order.getPrice())) * (Integer.parseInt(order.getQuantity()));
            Locale locale = new Locale("en", "US");

            NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
            txtTotalPrice.setText(fmt.format(total));
        }
    }else {
        Toast.makeText(getContext(), "No Cart Added", Toast.LENGTH_LONG).show();

    }
}

1 个答案:

答案 0 :(得分:0)

您正在自我加入表OrderDetails
在这种情况下,您必须为表的两个副本设置别名,例如:

OrderDetails as o1 LEFT JOIN OrderDetails as o2 ...

现在,在ON子句中,您必须正确限定列名,例如:

ON o1.user_id = o2.something

如果不这样做,则会收到该错误消息,因为列名user_id可能属于表的2个副本中的任何一个。
另外:
什么是session user_id?是列名吗?
如果是,那么问题在于它的名称中包含空格。
将其括在方括号中,因此statemnet应该为:

OrderDetails as o1 LEFT JOIN OrderDetails as o2
ON o1.user_id = o2.[session user_id]