I am working with sqlite where i have fired a query with "IN" operator but its taking to much time to display data. My query is following :
String Sql_query = "select id as _id,PARTY_NAME, PARTY_ADD1 as PARTY_ADD1,PARTY_KEY,PARTY_VAT from PARTYMAST where PARTY_KEY in( Select OUTACCD from OUTLETMST where OUTSMCD = " + salesman_code + " and Party_name like '" + etsearch.getText() + "%')";
Now to reducing time to get data i have made two cursors like below :
String Sql = "select id as _id,PARTY_NAME, PARTY_ADD1 as PARTY_ADD1,PARTY_KEY,PARTY_VAT from PARTYMAST";
String Sql2 = "Select OUTACCD from OUTLETMST where OUTSMCD = " + salesman_code + " and Party_name like '" + etsearch.getText() + "%')";
Cursor c1 = dbhelper.showdata(this,Sql);
Cursor c2 = dbhelper.showdata(this,Sql2);
Now i want to merge this two cursors c1 and c1 in one cursor like c1 + c2 = main_cursor
I have merged both cursor like following code :
MergeCursor merge_cursor = new MergeCursor(new Cursor[] {
c1, c2});
But it not worked in merge_cursor i getting only data of first cursor (c1).
Is it possible ? Please guide if anybody face this type of proble
Any other way to write this query ?
Thank you in advance.
You can use Join or Union for it.
Like for an example :-
sql = sql1;
sql += " UNION "
sql += sql2;
Related
I am running a query in sqllite browser which gives the output fine.
But when i am running the query through Android's SqlLiteDatabase's rawQuery function it returns 3 rows for every original row
The query being -
select s.shout_id, u.user_id, u.image_id , u.firstname, u.lastname, s.shout_msg , i.user_id 'r_user_id' , i.image_id 'r_img_id', i.firstname 'r_firstname', i.lastname 'r_lastname', s.rec_time from shouts s left join users u
on s.user_id = u.user_id left join users i on s.reciever_id = i.user_id
where ((s.user_id =1 and s.reciever_id =2) or (s.user_id =2 and s.reciever_id =1) ) and s.shout_id < 5 order by s.shout_id desc limit 20;
The raw query code being in android -
public Cursor get_friend_shouts_less(String myid, String friend_id, long shout_id) {
open();
Log.d("ListView1", "get less Message myid friend_id shout_id: " + myid + " " + friend_id + " " + shout_id );
Cursor c = db.rawQuery("select s.shout_id, u.user_id, u.image_id , u.firstname, u.lastname, s.shout_msg , i.user_id 'r_user_id' , i.image_id 'r_img_id', i.firstname 'r_firstname', i.lastname 'r_lastname', s.rec_time from shouts s left join users u " +
"on s.user_id = u.user_id left join users i on s.reciever_id = i.user_id" +
" where ((s.user_id =? and s.reciever_id =?) or (s.user_id =? and s.reciever_id =?) ) and s.shout_id < ? order by s.shout_id desc limit 60;", new String[]{myid, friend_id, friend_id, myid , String.valueOf(shout_id)});
return c;
}
Glad it worked, now my official Answer:
A SQL LEFT JOIN Operation is equal to an karthesian product AxB, which can lead to rows wih the same content. In "simple": using GROUP BY merges those identical rows.
How can I compare column content values? So if content values contain "ted" return all data in cursor.
public Cursor listNotes() {
String username = session.getUser();
String query = "SELECT * FROM Task WHERE " +help.Column_owner+ " = " +username ;
Cursor c = db.rawQuery(query, null);
return c;
}
Here is the error, I am trying to compare username to the content values in the column_create but its not working
no such column: ted (code 1): , while compiling: SELECT * FROM Notes WHERE column_owner = ted
username must be enclosed in apostrophes ('), because it is a string!
Correct your code like this:
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = '" +username + "'";
Or, better, use a bound parameter (in this case, Android takes care of the apostrophes for you and you're less prone to SQL injection - and, last but not least, you use less string concatenations):
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = ?";
Cursor c = db.rawQuery(query, new String[]{username});
I select data from my sqlite database. My problem is that when in database are apostrophes ("I' m John" - for example) and i try to select data, then my application crash.
If i don' t have apostrophes in database, then everything is all right.
My select data function:
String query = "SELECT * FROM " + mainCollumn + " WHERE used=0 " + " AND season <= " + seasons + " ORDER BY RANDOM() LIMIT " + count ;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor.moveToFirst()){
do {
Question question = new Question(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),
Integer.parseInt(cursor.getString(6)));
questionList.add(question);
}while(cursor.moveToNext());
}
Thanks for any help.
You can specially handle apostrophes by replacing them with double apostrophes, but the best way is to use query() with selectionArgs instead of rawQuery().
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[] {column1, column2}; // the columns you want
Cursor cursor = db.query(mainCollumn, String[] columns, "used=0 and season<=?", new String[] {seasons}, null, null, "RANDOM() LIMIT " + count);
This is an issue with any SQL as single quote (apostrophe) is the text delimiter character. In your data, you must either replace apostrophe with another character or replace single apostrophes with double apostrophes.
Daniel O'Neil
becomes
Daniel O''Neil
[EDIT]
UgglyNoodles's recommendation is better.
Hi, I am new to android. I want to write query for join in sqlite. My code is -
public Cursor SearchCategory(SQLiteDatabase db){
//return db.query("category_master", null, "status = 'Active'", null, null, null, null);
String Category_Sql = " select category_master.*,count(*) as cnt from product_master " +
" left join category_master on product_master.category_id = category_master.category_id " +
" where category_master.status = 'Active' group by category_master.category_id having cnt > 0 ";
return db.query(Category_Sql);
}
but it generate error. Where am I wrong?
It would have helped more if you could cite the error description.
Try running the query first in Portable SQLite explorer
you can use rawQuery
db.rawQuery("Select a.column1,b.column1 FROM table1 a JOIN table2 b ON a._id=b._id", null);
it should work
Background
I have an Android project that has a database with two tables: tbl_question and tbl_alternative.
To populate the views with questions and alternatives I am using cursors. There are no problems in getting the data I need until I try to join the two tables.
Tbl_question
-------------
_id
question
categoryid
Tbl_alternative
---------------
_id
questionid
categoryid
alternative
I want something like the following:
SELECT tbl_question.question, tbl_alternative.alternative where
categoryid=tbl_alternative.categoryid AND tbl_question._id =
tbl_alternative.questionid.`
This is my attempt:
public Cursor getAlternative(long categoryid) {
String[] columns = new String[] { KEY_Q_ID, KEY_IMAGE, KEY_QUESTION, KEY_ALT, KEY_QID};
String whereClause = KEY_CATEGORYID + "=" + categoryid +" AND "+ KEY_Q_ID +"="+ KEY_QID;
Cursor cursor = mDb.query(true, DBTABLE_QUESTION + " INNER JOIN "+ DBTABLE_ALTERNATIVE, columns, whereClause, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
I find this way to form queries harder than regular SQL, but have gotten the advice to use this way since it is less error prone.
Question
How do I join two SQLite tables in my application?
You need rawQuery method.
Example:
private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
Use ? bindings instead of putting values into raw sql query.
An alternate way is to construct a view which is then queried just like a table.
In many database managers using a view can result in better performance.
CREATE VIEW xyz SELECT q.question, a.alternative
FROM tbl_question AS q, tbl_alternative AS a
WHERE q.categoryid = a.categoryid
AND q._id = a.questionid;
This is from memory so there may be some syntactic issues.
http://www.sqlite.org/lang_createview.html
I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.
In addition to #pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this
SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1
via raw query like this -
String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
+ " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
+ " WHERE " + RefuelTable.ID + " = " + id;
Cursor c = db.rawQuery(
rawQuery,
null
);
because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -
SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1
and hence be able to take advanatage of the SQLiteDatabase.query() helper method
Cursor c = db.query(
RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " + id,
null,
null,
null,
null
);
For a detailed blog post check this
http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery
"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.
Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.
select P.*
from product_has_image P
inner join highest_priority_images H
on (H.id_product = P.id_product and H.priority = p.priority)