I have two tables. In those tables, my stop id might be in one of them or both of them. If my stop id doesnt exist in B, it should pick from A. And if it doesnt exist in A, it should pick from B. And if stop id exist in both tables then I want to give priority to B and retrieve the row from B. Below query always returns the value from B. Can you help me out to fix this?
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});
In your UNION ALL you should apply the WHERE clause to both SELECTs; your current code applies the condition to only the B side, while the A side returns all rows. LIMIT 1 at the end hides this problem, though.
String concatenation does not make it easy to see, but you should be passing id twice, and using two ? placeholders in your query:
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
Related
I want to insert the SUM of Somme_versee (column in table Versement) in the column Versement_total.
This is a part of my code:
statement.executeUpdate("INSERT INTO Versement ( Nom , Prenom, Date , Somme_versee,Prix_du_logement, Nom_du_projet) VALUES('" + nom.getText() +"','" +prenom.getText() +"','" +date.getText() + "'," + verse.getText() + ", " + "(SELECT Prix_du_logement FROM Client WHERE Nom='"+ nom.getText() +"' AND Prenom='"+ prenom.getText() + "')," + " (SELECT Nom_du_projet FROM Client WHERE Nom='" + nom.getText()+ "' AND Prenom='" +prenom.getText() + "'))");
statement.executeUpdate("UPDATE Versement SET Versement_total= SUM(Somme_versee) " );
When executing I get this error: misuse of aggregate function SUM()
You should never do this in the same table. And it will get worse when the table gets more records. But what you seem to want is:
UPDATE Versement SET Versement_total = (SELECT SUM(Somme_versee) FROM Versement)
I have an application that works well. But I suspect that I can improve it if I optimize queries to the database. And I need suggestions.
This is part of my "select query":
private static final String SELECT = "SELECT " +
"dz.first_id AS first_id, " +
"dz._id AS _id, " +
"dz.att1 AS att1, " +
"dz.att2 AS att2, " +
"dz.att3 AS att3, " +
"dz.att4 AS att4, " +
"dz.att5 AS att5, " +
"d.var1 AS var1, " +
"d.name AS name, " +
"d.last_update AS last_update, " +
"d.image_url AS image_url, " +
"d.image_highlighted_url AS image_highlighted_url, " +
"d.var2 AS var2, " +
"d.type AS type, " +
"d.state AS state, " +
"d.sync AS sync, " +
"d.var3 AS var3 " +
"FROM table1 dz INNER JOIN table2 d " +
"ON d._id = dz.first_id ";
Cursor result = conn.rawQuery(SELECT, null);
*table1 and table2 have simple creation: only one _id integer PRIMARY KEY AUTOINCREMENT NOT NULL
It is useful to use views? Any other suggestion?
Thanks.
This query looks as cut and dry and they can get, I think your options are really either to see if you can somehow leave some unnecessary columns out of your select or alternatively to see that both dz.first_id and d._id have indexes setup. Perhaps add a index to dz with the following
CREATE INDEX index1 ON table1 (first_id);
I have a database for my leaderboard. Currently, I insert all scores into my leaderboard, and select the 5 highest scores to show on my app. I think it would take up too much room to never delete the other scores, so I would like to delete them. How can I do this?
Here's how I select the top 5 scores, ranked first by score and second by time if score is equal:
public Cursor gethmLeaderboard(SQLiteDatabase db){
String[] columns = {TableInfo.LB_RANK, TableInfo.LB_SCORE, TableInfo.LB_TIME};
Cursor c = db.query(TableInfo.TABLE_HM, null, null, null, null, null, TableInfo.LB_SCORE + " DESC, " + TableInfo.LB_TIME + " ASC", "5");
return c;
}
Here's how I create my table:
public String CREATE_HMQUERY = "CREATE TABLE " + TableInfo.TABLE_HM + "("
+ TableInfo.LB_RANK + " INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 1 ," + TableInfo.LB_SCORE +
" INT,"+ TableInfo.LB_TIME + " VARCHAR );";
I want to delete all rows NOT IN that query. How can I do that?
Edit:
I tried this query:
public String DEL_ALLBUTES = "DELETE FROM " +
TableInfo.TABLE_HM + " WHERE " +
TableInfo.LB_RANK + " NOT IN (SELECT " +
TableInfo.LB_RANK + " FROM " +
TableInfo.TABLE_HM + " ORDER BY " +
TableInfo.LB_SCORE + " DESC, " +
TableInfo.LB_TIME + " ASC LIMIT 5);";
In this format:
db.rawQuery(DEL_ALLBUTES, null);
But when I check the database there are still tons of rows so it doesn't work.
Your table needs to have some unique ID. Use that to identify the rows you want to keep:
DELETE FROM ES
WHERE ID NOT IN (SELECT ID
FROM ES
ORDER BY Score DESC, Time ASC
LIMIT 5);
You can create temp table insert top 5 score into temp table and delete all table then insert temp table into main table.
CREATE TEMP TABLE TempES AS SELECT
ID
FROM
ES
ORDER BY
Score DESC,
Time ASC
LIMIT 5;
DELETE
FROM
ES;
INSERT INTO ES SELECT
*
FROM
TempES;
DROP TABLE TempES;
I have a ResultSet that I know contains 8 rows of data because I checked it with a direct query of the DB. My code will only display the first row.
If anyone can give me some help I would greatly appreciate it. The first row is what should I expect it to be, I just don't know how to get it to move on to print subsequent rows.
term= Integer.parseInt(args[1]);
// Select a list of the surveys that fall under the term
query= "Select cid,subject,course_number,instructor_id from Courses where term=" + Integer.parseInt(args[1]);
result = statement.executeQuery(query);
String query2="";
while(result.next())
{
// Pull in the data
cid = result.getInt("cid");
subject = result.getString("subject");
courseNumber= result.getInt("course_number");
instructorId= result.getInt("instructor_id");enter code here
// Get the instructors last name
query2= "Select last_name from Instructors where fid=" + instructorId;
subResult= statement.executeQuery(query2);
while(subResult.next())
{
instructorLName= subResult.getString(1);
}
// Get the averages and num submitted
query2= "Select num_submitted, sum_q1, sum_q2, sum_q3, sum_q4, survey_id from surveys where cid=" + cid;
subResult= statement.executeQuery(query2);
while(subResult.next())
{
numSub= subResult.getInt(1);
sumQ1= subResult.getInt(2);
sumQ2= subResult.getInt(3);
sumQ3= subResult.getInt(4);
sumQ4= subResult.getInt(5);
surveyId= subResult.getInt(6);
}
// Print everything necessary
System.out.println( surveyId + " " + term + " " + subject + " " + courseNumber +
" " + instructorLName + " " + sumQ1/numSub + " " + sumQ2/numSub + " " + sumQ3/numSub
+ " " + sumQ4/numSub);
}
}
Not sure, but the problem might be that you are using same Statement object to execute different queries. Create separate statement instances for query and query2 and try.
So the program is the connecting to a .mdb file as our data base. I have written all the other code to the program and know it works fine but I am now having trouble with a complex SQL statement being passed as a parameter to a createQuery(Sring, int) method.
There are two tables
Person, which has Name, Id, City, State
Classes, which has Id, Course, Grade
The intended purpose of this line is to print out "Name and Id" from a table of Persons and also print "Course and Grade" from the Classes table. The query only prints entries with matching Id's(Person.Id = Classes.Id), in a specific Course('CSC 225'), and that have a Grade > 70.
We never were taught the SQL statements in any depth so my basic understanding has concocted the following lines of code.
String s = "SELECT " + personTableTitle + ".Name, " + personTableTitle + ".Id, " +
classesTableTitle + ".Course, " + classesTableTitle + ".Grade FROM " +
personTableTitle + " " + classesTableTitle + " WHERE " +
personTableTitle + ".ID = " + classesTableTitle + ".Id AND " +
"Course = 'CIS 225' AND " + classesTableTitle + ".Grade > 70 AND " +
personTableTitle + ".Id = ? AND " + classesTableTitle + ".Id = ?";
System.out.print(s); // Double check of my SQL Statement before passing
db.createQuery(s, 4);
I have been playing with this SQL statement since Wednesday night and haven't been having much luck.
I only see two problems. Sql needs commas between the table names in the FROM clause, i.e. ...FROM table1, table2 WHERE.... So change your line to
personTableTitle + ", " + classesTableTitle + " WHERE " +
This next one might not be a problem, but it's a good idea to include the table name in front of every field reference.
classesTableTitle + ".Course = 'CIS 225' AND " + classesTableTitle + ".Grade > 70 AND " +
You should definitely try your query directly on the database (console or GUI). Once your query is valid, you'll be able to translate it very quickly back into Java.
Otherwise, it's good practice to add an alias to tables; for example:
select *
from Person P, Classes C
where P.Name = 'joe' and P.id = C.id
You may also need to do an outer join to get your data (look at how to do joins for your database).
Here's what I would suggest for SQL code
String s = "SELECT P.Name, P.Id, ";
s = s + "C.Course, C.Grade ";
s = s + "FROM Person P ";
s = s + "JOIN Classes C ";
s = s + "ON P.ID = C.ID ";
s = s + "WHERE Course = 'CIS 225' AND C.Grade > 70;";
I split up each assignment into its own line.
Solved it everyone, thanks for the help.
I started rewriting it using the suggestions posted and came up with this as the string:
String s = "SELECT Person2.Name, Person2.Id, Classes.Course, Classes.Grade FROM Person2, Classes WHERE Classes.Id = Person2.Id AND Classes.Course = 'CIS 225' AND Classes.Grade >70";
It works so I can make it more presentable now. The reason I am using my variable names from java in the original post was that is what the teacher wanted. She is very stubborn and has taken off points from my material for things as simple as writings += whatever; instead of s = s + whatever;