UNION in SQLiteDatabase? - java

I need to execute the following query, and return a Cursor, using SQLiteDatabase class:
SELECT DISTINCT sender
FROM messages;
UNION
SELECT DISTINCT recipient
FROM messages;
(the fields sender and recipient are of the same type.)
I know how to execute the SELECT DISTINCT and get 2 cursors holding sender and recipient columns:
c1 = db.query(
true, //distinct
Messages.TABLE_NAME, //table name
senderColumn, //columns
null, //where clause
null, //where args
null, //group
null, //having
sortOrder, //sorting order
null //limit of rows number
);
c2 = db.query(
true, //distinct
Messages.TABLE_NAME, //table name
recipientColumn, //columns
null, //where clause
null, //where args
null, //group
null, //having
sortOrder, //sorting order
null //limit of rows number
);
But I can't figure how to UNION them (and return a Cursor). Also, I may want to specify a sorting order on the result. How can I do that? I can't find any mention of UNION in the API.

Related

How i make a Addition from 2 tables and insert the value to one of them

I cant find the right query that make an addition from 2 tables 2 columns inserts and save the data to one of them
Here is my makeorderaction
private void Make_OrderActionPerformed(java.awt.event.ActionEvent evt) {
String query="INSERT INTO Orders(Pro_Id ,Pro_Name,Order_Quantity,Order_Date)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Order_Quantity.getText()+" ','"+Order_Date.getText()+" ') ";
executeSQLQuery(query,"Inserted");
String qquery ="UPDATE Products SET Pro_Quantity where Prod_Id = Pro_Quantity+Order_Quantity ";
// executeSQLQuery(query,"quantity updated");
}
I need to find a sqlquery that make addition from table Order the column Order_Quantity with the table products the column Pro_Quantity. And make an update in table products the new value in column Pro_Quantity depending each time the identifier of the product any idea ? Ty
Table Orders
CREATE TABLE [dbo].[Orders](
[Order_Id] [int] IDENTITY(1,1) NOT NULL,
[Order_Date] [int] NULL,
[Order_Quantity] [int] NULL,
[Pro_Id] [int] NULL,
[Pro_Name] [varchar](50) NULL,
CONSTRAINT [PK__Orders__F1E4607B714E3A74] PRIMARY KEY CLUSTERED
(
[Order_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Orders] WITH CHECK ADD CONSTRAINT [FK_Orders_Products] FOREIGN KEY([Pro_Id])
REFERENCES [dbo].[Products] ([Pro_Id])
GO
ALTER TABLE [dbo].[Orders] CHECK CONSTRAINT [FK_Orders_Products]
GO
Table Products
CREATE TABLE [dbo].[Products](
[Pro_Id] [int] NOT NULL,
[Pro_Name] [varchar](50) NOT NULL,
[Pro_Price] [float] NULL,
[Pro_Quantity] [int] NULL,
[Pro_Supplier_id] [int] NOT NULL,
[Pro_Tax] [float] NOT NULL,
[Cat_products] [varchar](50) NULL,
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[Pro_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
I add this qquery but i think he need some changes
String qquery= " UPDATE Products SET Pro_Quantity= Pro_Quantity + '"+Order_Quantity.getText()+"' FROM Products INNER JOIN Orders ON Products.Pro_Id="+Orders.getText() ;
some think like this
How do I UPDATE from a SELECT in SQL Server?
UPDATE P
SET
P.Pro_Quantity= P.Pro_Quantity + O.Order_Quantity
FROM
Products as P
INNER JOIN Orders as O
ON P.Pro_Id= O.Pro_Id
i change the above code a bit so he update the last order only.
String query= " UPDATE Products SET Pro_Quantity= Products.Pro_Quantity + Orders.Order_Quantity FROM Products INNER JOIN Orders ON Products.Pro_Id= Orders.Pro_Id where Order_Id = (SELECT MAX(Order_Id) FROM Orders)" ;
executeSQLQuery(query,"updated");

How can I get a value from database that has the soonest time to current time?

I keep getting a NullPointerException when I try this query:
Cursor cursor = sqLiteDatabase.query("collection", new String[] { "SELECT interval WHERE MIN(time) FROM collection" }, null, null,
null, null, null); // This is where the NPE is.
cursor.moveToFirst(); //ADD THIS!
Integer collectionInterval = cursor.getInt(0);
Is my select query right or the way I'm setting this up?
Basically above I want to select an interval where the soonest time to current time from a table. How can I do that?
In a query, FROM comes before WHERE. Also, I think you need an equality test there
SELECT interval FROM collection WHERE time = (SELECT MIN(time) FROM collection)

How can I read only 10 rows from my Sql Database?

Hey I have a question:) How can I read only ten rows from my sql db?
here is my code:
openDB();
Cursor c = myDb.getSpalte();
List<Integer> valueList = new ArrayList<Integer>(c.getCount());
while (c.moveToNext()) {
valueList.add(c.getInt(1));
}
c.close();
closeDB();
And if it helps you here is my getSpalte method:
public Cursor getSpalte(){
String where = null;
String Order = "_id DESC";
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Thank yout for helping! And sorry for my bad englsih;P
Set the last null argument to "10". This argument is for LIMIT which limits the number of rows returned by the query.
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, "10");
Remember though that limiting must be accompanied by appropriate logic to sort the result set. Otherwise, you can get any 10 rows, which may not always be what you want.
Reference
Change your db query in your getSpalte function like this:
Cursor c = db.query(true, DATABASE_TABLE, KEY_KALOA,
where, null, null, null, Order, "10");
You can do this by using select TOP, limit or using ROWNUM depending on the DB you use, or you can simple handle it using a simple for loop instead of while.
You can use LIMIT for that as last argument. Here 10.
Refer here
limit - Limits the number of rows returned by the query, formatted as
LIMIT clause. Passing null denotes no LIMIT clause.

How to get Group ID of contacts Number (Android)

How to get Group ID knowing contact's Number
I guess it have to be another query inside this one, but I have not ANY idea how to do it
Here what I've tried:
String[] projection = new String[]{ ContactsContract.Groups._ID };
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.NUMBER +" = "+ number,
null,
null);
cursor.moveToNext();
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Groups._ID));
(Query returns nothing)
Thanks for help!
Your query returns nothing, because there is no such column Groups._ID within dataset CommonDataKinds.Phone.
Try something like this:
String sPhoneNumber = "+48123456789";
Cursor cursor = getApplicationContext().getContentResolver().query(
Data.CONTENT_URI, new String[] {CommonDataKinds.GroupMembership._ID},
ContactsContract.CommonDataKinds.Phone.NUMBER+"='"+sPhoneNumber+"'", null, null);
where sPhoneNumber is String with desired phone number. Keep in mind, that your cursor may still return 0 depending on:
how your phone number is formatted, i.e. you wish to find group ID
for contact of given number +49123456789 while number is formatted
like this +49 123 456 789. Whitespaces are making this completely
different String.
your contact does not belong to any group.
Also cursor can still return more results, mostly in cases when your contact belongs to more than one group.

How do I update the field of a table with the count of another table? SQLite, Java, Android

I'm getting an "Invalid Character Constant" under the " 'D " just after UPDATE. Any Ideas?
ORIGINAL :
public Cursor fetchAllJournals(String sort) {
mDb.rawQuery(UPDATE 'DATABASE_JOURNAL_TABLE'
SET 'KEY_JOURNAL_NOTES' =
(SELECT COUNT(*) FROM 'DATABASE_HOMES_TABLE'
WHERE 'DATABASE_JOURNAL_TABLE'.'KEY_JROWID' = 'DATABASE_HOMES_TABLE'.'KEY_HOME_JOURNALID')
)
return mDb.query(DATABASE_JOURNAL_TABLE, new String[] {KEY_JROWID,
KEY_JOURNAL_TITLE, KEY_JOURNAL_NOTES, KEY_JDATE},null , null, null, null, sort ,null);
}
ANSWER:
public Cursor fetchAllJournals(String sort) {
mDb.execSQL("UPDATE "+DATABASE_JOURNAL_TABLE+" SET "+KEY_JOURNAL_NOTES+" " +
" = (SELECT COUNT(*) FROM "+DATABASE_HOMES_TABLE+" WHERE "
+DATABASE_JOURNAL_TABLE+"."+KEY_JROWID+" = "+DATABASE_HOMES_TABLE +"." + KEY_HOME_JOURNALID+")");
return mDb.query(DATABASE_JOURNAL_TABLE, new String[] {KEY_JROWID,
KEY_JOURNAL_TITLE, KEY_JOURNAL_NOTES, KEY_JDATE},null , null, null, null, sort ,null);
}
The invalid character constant in this case is 'DATABASE_JOURNAL_TABLE'. Single quotes in Java define a character constant, i.e. one character, e.g. 'a' or 'b' or '!'. 'DATABASE_JOURNAL_TABLE' is a string of them so you have to use a String literal and double quotes, i.e. "prefix "+DATABASE_JOURNAL_TABLE+" suffix".
Try this:
public Cursor fetchAllJournals(String sort) {
mDb.rawQuery("UPDATE "+DATABASE_JOURNAL_TABLE+" SET "+KEY_JOURNAL_NOTES+" = (SELECT COUNT(*) FROM "+DATABASE_HOMES_TABLE+"WHERE "+DATABASE_JOURNAL_TABLE+"."+KEY_JROWID+" =+"DATABASE_HOMES_TABLE"+."+KEY_HOME_JOURNALID+")");
return mDb.query(DATABASE_JOURNAL_TABLE, new String[] {KEY_JROWID, KEY_JOURNAL_TITLE, KEY_JOURNAL_NOTES, KEY_JDATE},null , null, null, null, sort ,null);
}

Categories

Resources