Selecting Items from another table using ID - java

I have two tables Item and a table which records the items in each order (Junction Table)
ITEM Table
String itemTable = "CREATE TABLE " + ITEM_TABLE + " ("
+ ID_ITEM + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ITEM_NAME + " TEXT,"
+ ITEM_TYPE + " TEXT,"
+ ITEM_PRICE + " TEXT);";
ORDER_ITEM Table
String orderItemTable = "CREATE TABLE " + ORDER_ITEM_TABLE + " ("
+ ID_ORDER_ITEM + " INTEGER,"
+ ID_ITEM_ORDER + " INTEGER,"
+ " FOREIGN KEY ("+ID_ORDER_ITEM+") REFERENCES "+ EMP_TABLE +"("+ ID_EMP +"), "
+ " FOREIGN KEY ("+ID_ITEM_ORDER+") REFERENCES "+ EMP_TABLE +"("+ ID_EMP +"));";
Data in the ORDER_ITEM table each Item id refers to a specific item in the item table this is what I am trying to refer to and use to pull data from the DB.
At the moment I can pull the Item id from this table but not the actual Item using the Id. Here idOrder is passed when the order is selected
String selctAllEmployeesOrdersItems = "SELECT * FROM " + ORDER_ITEM_TABLE + " WHERE " + ID_ORDER_ITEM + " = " + idOrder;
One way of achieving what I want is by storing the Item ID's in a ArrayList and iterating over this to select all of the Items but I know there is a better way.
Some research I have seen has suggested that I join the tables referencing the ITEM ID but I am not sure of the correct syntax. The dot notation does not work with this query.
String selctAllEmployeesOrdersItems = "SELECT * FROM " + ORDER_ITEM_TABLE + " WHERE " + ID_ORDER_ITEM + " = " + idOrder
+ " JOIN " + ITEM_TABLE + " ON " + ORDER_ITEM_TABLE+"."+ID_ITEM_ORDER + " = " + ITEM_TABLE+"."+ID_ITEM;
The error message being show is
Caused by: android.database.sqlite.SQLiteException: near "JOIN":
syntax error (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM
ORDER_ITEM_TABLE WHERE ID_Order = 1 JOIN ITEM_TABLE ON
ORDER_ITEM_TABLE.ID_Item = ITEM_TABLE.ID

The syntax of your SQL statement is wrong.
The WHERE clause must be written after the join:
String selctAllEmployeesOrdersItems =
"SELECT * FROM " + ORDER_ITEM_TABLE + " AS o " +
"INNER JOIN " + ITEM_TABLE + " AS i ON o." + ID_ITEM_ORDER + " = i." + ID_ITEM + " " +
"WHERE o." + ID_ORDER_ITEM + " = " + idOrder;
Note the use of aliases o and i for the 2 tables that shortens significantly the code.
Also, the definition of the table ORDER_ITEM:
String orderItemTable = "CREATE TABLE " + ORDER_ITEM_TABLE + " ("
+ ID_ORDER_ITEM + " INTEGER,"
+ ID_ITEM_ORDER + " INTEGER,"
+ " FOREIGN KEY ("+ID_ORDER_ITEM+") REFERENCES "+ EMP_TABLE +"("+ ID_EMP +"), "
+ " FOREIGN KEY ("+ID_ITEM_ORDER+") REFERENCES "+ EMP_TABLE +"("+ ID_EMP +"));";
does not seem correct.
What is the table EMP_TABLE?
Why do both columns ID_ORDER_ITEM and ID_ITEM_ORDER reference the same column?
This does not make sense.

I believe you have the clauses in the wrong order, this should be:
select ... from ... join ... on ... where ...
So in this case:
SELECT * FROM
ORDER_ITEM_TABLE JOIN ITEM_TABLE
ON ORDER_ITEM_TABLE.ID_Item = ITEM_TABLE.ID
WHERE ORDER_ITEM_TABLE.ID_Order=1;

The where clause goes after the join. I would also recommend using table aliases to shorten the query and make it more readable. Finally, you probably want to select columns from the items table only, not from the junction table (which you are filtering on already):
SELECT i.*
FROM ORDER_ITEM_TABLE oi
JOIN ITEM_TABLE i ON oi.ID_Item = i.ID
WHERE oi.ID_Order = 1

Related

From Javafile to SQL query - Minecraft plugin

as i am working on a minecraft server some plugin does not make a certain table itself.
For who is interested: https://www.spigotmc.org/resources/craftconomy.2395/
But in the github files i found the java script where it does generate the needed table.
public final String createTableMySQL = "CREATE TABLE IF NOT EXISTS " + getPrefix() + TABLE_NAME + " (" +
" `" + BALANCE_FIELD + "` double DEFAULT NULL," +
" `" + WORLD_NAME_FIELD + "` varchar(255)," +
" `username_id` int(11)," +
" `" + CURRENCY_FIELD + "` varchar(50)," +
" PRIMARY KEY (" + WORLD_NAME_FIELD + ", username_id, currency_id)," +
" CONSTRAINT `"+getPrefix()+"fk_balance_account`" +
" FOREIGN KEY (username_id)" +
" REFERENCES " + getPrefix() + AccountTable.TABLE_NAME + "(id) ON UPDATE CASCADE ON DELETE CASCADE," +
" CONSTRAINT `"+getPrefix()+"fk_balance_currency`" +
" FOREIGN KEY (" + CURRENCY_FIELD + ")" +
" REFERENCES " + getPrefix() + CurrencyTable.TABLE_NAME +"(name) ON UPDATE CASCADE ON DELETE CASCADE" +
") ENGINE=InnoDB CHARSET=utf8;";
Could someone help me to make a SQL query out of this, which just can be dropped into PHPMyadmin?
Thanks already for reading.
I already solved it myself, no reason for reaction anymore.

QuerySyntaxException: expecting OPEN, found 'DESC' near line 1

I want to implement this JPQL query using JPA:
String hql = "SELECT new org.plugin.service.PaymentTransactionsDeclineReasonsDTO(count(e.id) as count, e.status, e.error_class, e.error_message) " +
" FROM " + PaymentTransactions.class.getName() + " e " +
" WHERE e.terminal_id = :terminal_id AND (e.createdAt > :created_at) " +
" AND (e.status != 'approved') " +
" GROUP BY e.error_message " +
" ORDER BY count DESC";
But I get error: Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting OPEN, found 'DESC' near line 1, column 334 [SELECT new org.plugin.service.PaymentTransactionsDeclineReasonsDTO(count(e.id) as count, e.status, e.error_class, e.error_message) FROM org.datalis.plugin.entity.PaymentTransactions e WHERE e.terminal_id = :terminal_id AND (e.createdAt > :created_at) AND (e.status != 'approved') GROUP BY e.error_message ORDER BY count DESC]
What is the proper way to order by count?
You cannot use the SQL keyword COUNT as an alias (not even in lower case). There is no way around it, you have to use alias names that are not SQL keywords (like SELECT, FROM, AS and so on).
I think you should use the following query, which will at least get rid of the error you posted:
String hql = "SELECT "
+ "new org.plugin.service.PaymentTransactionsDeclineReasonsDTO("
+ "count(e.id) as amount, " // <--- alias name changed here
+ "e.status, "
+ "e.error_class, "
+ "e.error_message) "
+ "FROM "
+ PaymentTransactions.class.getName() + " e "
+ "WHERE "
+ "e.terminal_id = :terminal_id "
+ "AND (e.createdAt > :created_at) "
+ "AND (e.status != 'approved') "
+ " GROUP BY e.error_message "
+ " ORDER BY amount DESC"; // <-- alias name used here

SQLite How To - Sum by Value in a JOIN

I have a sample sqlite database that currently has 7 entries which is queried via:
String selectQuery = "SELECT * FROM " + TABLE_TRANSACTIONS + " x " +
"JOIN (SELECT " + KEY_TYPE_ID + ", COUNT(*) count FROM " + TABLE_TRANSACTIONS + " GROUP BY " + KEY_TYPE_ID + " ORDER BY count DESC) y " +
"ON x.type_id = y.type_id " + //type_id vs. KEY_TYPE_ID as alias won't recognize KEY_TYPE_ID
"WHERE x.type_id = " + TagData.TYPE_EXPENSE;
The output is:
Type A = 2500
Type A = 2599
Type B = 45000
Type C = 299
Type C = 2699
Type C = 10000
Type C = 12000
which correctly groups my types by their respective values. However, the ideal output would be:
Type B = 45000
Type C = 24998
Type A = 5099
where each type is then ordered by the sum of each type. Is this possible? If so what else should I be doing in my query? I'm relatively new to SQL and haven't been able to figure this out yet. Thank you in advance for any insight.
EDIT
Based on your input #CL. I now have a more simplified query:
String selectQuery = "SELECT *, SUM(" + KEY_AMOUNT + ") AS amount_sum " +
"FROM " + TABLE_TRANSACTIONS + " " +
"GROUP BY " + KEY_LABEL_ID + " " +
"ORDER BY amount_sum DESC";
which works as expected when I use sqlfiddle at http://www.sqlfiddle.com/#!5/b3615/1 but not when I use the query in Android. In Android, only the most recent entry for each label type is returned. The SUM doesn't seem to actually do its job.
What am I missing here?
Moving the aggregation and ordering into a subquery does not make sense.
If you want to get the count of all expense transactions per type, just use a simple aggregation:
SELECT Type_ID,
COUNT(*) count
FROM TRANSACTIONS
WHERE TYPE_IF = 'TYPE_EXPENSE'
GROUP BY TYPE_ID
ORDER BY count DESC
This is an aggregation query. Fortunately, SQLite supports CTEs, so you can just do something like this:
with t as (
<your query here>
)
select type, sum(value) as sumv
from t
group by type
order by sumv desc;
Even without the with clause, you could just use your query as a subquery.
You would, of course, use the appropriate column names in the query.
#CL. Your response led me down the correct path, for those interested here is the resulting query that achieved what I was after:
String selectQuery = "SELECT " + KEY_LABEL_ID + ", " + " SUM(" + KEY_AMOUNT + ") as total, " + KEY_TYPE_ID + " " +
"FROM (" +
"SELECT " + KEY_LABEL_ID + ", " + KEY_AMOUNT + ", " + KEY_TYPE_ID + " " +
"FROM " + TABLE_TRANSACTIONS + " " +
") as trans_table " +
"WHERE " + KEY_TYPE_ID + " = " + TagData.TYPE_EXPENSE + " " +
"GROUP BY " + KEY_LABEL_ID + " " +
"ORDER BY total DESC";

java.sql.SQLException: ORA-00936: missing expression

Below I am creating table.
public static final String CREATE_SQL = "CREATE TABLE " +DATABASE_TABLE +
"(ID number(10,0), " +
" CGUID VARCHAR(255), " +
" PGUID VARCHAR(255), " +
" SGUID VARCHAR(255), " +
" USERID VARCHAR(255), " +
" ULOC VARCHAR(255), " +
" SLOC VARCHAR(255), " +
" PLOC VARCHAR(255), " +
" ALOC VARCHAR(255), " +
" SITEID VARCHAR(255), " +
" ATTRIBUTEID VARCHAR(255), " +
" ATTRIBUTEVALUE VARCHAR(255), " +
" PRIMARY KEY ( ID ))";
This is the below UPSERT_SQL query when I am trying to update my database table I am always getting- java.sql.SQLException: ORA-00936: missing expression
. I checked my SQL, I am not able to find where the expression is missing. Is something wrong with the below SQL?
public static final String UPSERT_SQL = "MERGE INTO " +DATABASE_TABLE+ " USING ( SELECT ? AS ID, " + // We will maybe add this record
" ? AS CGUID, " +
" ? AS PGUID, " +
" ? AS SGUID, "+
" ? AS USERID, "+
" ? AS ULOC, "+
" ? AS SLOC, "+
" ? AS PLOC, "+
" ? AS ALOC, "+
" ? AS SITEID, "+
" ? AS ATTRIBUTEID, "+
" ? AS ATTRIBUTEVALUE, "+
" FROM dual ) maybe "+
" ON (maybe.ID = "+DATABASE_TABLE+".ID) "+
" WHEN MATCHED THEN "+
// We only need update the fields that might have changed
" UPDATE SET " +DATABASE_TABLE+ ".ULOC = maybe.ULOC, " +DATABASE_TABLE+ ".SLOC = maybe.SLOC, " +DATABASE_TABLE+ ".PLOC = maybe.PLOC, " +DATABASE_TABLE+ ".ALOC = maybe.ALOC "+
" WHEN NOT MATCHED THEN "+
// Insert new record
" INSERT VALUES (maybe.ID, maybe.CGUID, maybe.PGUID, maybe.SGUID, maybe.USERID, maybe.ULOC, maybe.SLOC, maybe.PLOC, maybe.ALOC, maybe.SITEID, maybe.ATTRIBUTEID, maybe.ATTRIBUTEVALUE)";
And from below I am executing that UPSERT_SQL Statement.
LnPDataConstants.PSTMT = LnPDataConstants.DB_CONNECTION.prepareStatement(LnPDataConstants.UPSERT_SQL); // create a statement
LnPDataConstants.PSTMT.setInt(1, (int) ind);
LnPDataConstants.PSTMT.setString(2, LnPDataConstants.CGUID_VALUE);
LnPDataConstants.PSTMT.setString(3, LnPDataConstants.PGUID_VALUE);
LnPDataConstants.PSTMT.setString(4, LnPDataConstants.SGUID_VALUE);
LnPDataConstants.PSTMT.setString(5, LnPDataConstants.UID_VALUE);
LnPDataConstants.PSTMT.setString(6, LnPDataConstants.ULOC_VALUE);
LnPDataConstants.PSTMT.setString(7, LnPDataConstants.SLOC_VALUE);
LnPDataConstants.PSTMT.setString(8, LnPDataConstants.PLOC_VALUE);
LnPDataConstants.PSTMT.setString(9, LnPDataConstants.ALOC_VALUE);
LnPDataConstants.PSTMT.setString(10, LnPDataConstants.SITEID_VALUE);
LnPDataConstants.PSTMT.setString(11, "10200");
LnPDataConstants.PSTMT.setString(12, attrValue1.toString().split("=")[1]);
LnPDataConstants.PSTMT.executeUpdate();
Yes, there is something wrong with the SQL, and it is that you wrote a comma before FROM dual. This causes Oracle's SQL parser to complain.

Android SQLite : constraint failed error code 19

I have execute the following sql:
update record set out_payment=4 where out_payment=4;
the out_payment of record is defined as Integer and reference the Payment(id)
I can ensure the 4 was the one of the ID of the payment table;
but I still got the constrained failed....
07-31 10:20:36.014: ERROR/Database(19085): Error updating out_payment=4 using UPDATE record_table SET out_payment=? WHERE out_payment = 4
07-31 10:20:45.964: ERROR/AndroidRuntime(19085): FATAL EXCEPTION: main
07-31 10:20:45.964: ERROR/AndroidRuntime(19085): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
the code is as following:
values.clear();
values.put(RecordSchema.ID_OUT_PAYMENT, oldid);
selection = RecordSchema.ID_OUT_PAYMENT + " = " + oldid + "";
this.db.update(Table.RECORD, values, selection, null);
the Schema is as following :
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE.RECORD
+ " (" + RecordSchema.ID + " INTEGER PRIMARY KEY"
+ "," + RecordSchema.AMOUNT + " TEXT NOT NULL"
+ "," + RecordSchema.ID_CATEGORY + " INTEGER NOT NULL"
+ "," + RecordSchema.ID_SUBCATEGORY + " INTEGER"
+ "," + RecordSchema.DATE + " DATE NOT NULL"
+ "," + RecordSchema.ID_IN_PAYMENT + " INTEGER"
+ "," + RecordSchema.ID_OUT_PAYMENT + " INTEGER"
+ ",FOREIGN KEY(" + RecordSchema.ID_CATEGORY + ") REFERENCES "
+ IsAiZanTable.CATEGORY + "(" + CategorySchema.ID + ") ON UPDATE CASCADE"
+ ",FOREIGN KEY(" + RecordSchema.ID_SUBCATEGORY + ") REFERENCES "
+ IsAiZanTable.SUBCATEGORY + "(" + SubcategorySchema.ID + ") ON UPDATE CASCADE"
+ ",FOREIGN KEY(" + RecordSchema.ID_IN_PAYMENT + ") REFERENCES "
+ IsAiZanTable.PAYMENT + "(" + PaymentSchema.ID + ") ON UPDATE CASCADE"
+ ",FOREIGN KEY(" + RecordSchema.ID_OUT_PAYMENT + ") REFERENCES "
+ IsAiZanTable.PAYMENT + "(" + PaymentSchema.ID + ") ON UPDATE CASCADE"
+ ");");
db.execSQL("CREATE TABLE IF NOT EXISTS " +Table.PAYMENT
+ " (" + PaymentSchema.ID + " INTEGER PRIMARY KEY"
+ "," + PaymentSchema.KIND + " INTEGER NOT NULL"
+ "," + PaymentSchema.NAME + " TEXT NOT NULL UNIQUE"
+ "," + PaymentSchema.TOTAL + " TEXT NOT NULL"
+ "," + PaymentSchema.HIDDEN + " INTEGER NOT NULL"
+ ");");
Any body can help me to solve this problem?
Actually I want to update the id from 4 to 5
I can ensure both 4 and 5 are the exist IDs of the payment table.
But the same problem occurred, so I update 4 to 4 is the same.
I think if I can solve the problem of 4 to 4 , I should solve the problem of 4 to 5 .
Many thanks for your answer!!
I have found the answer.
One of my team run the following
db.execSQL("PRAGMA foreign_keys = OFF;");
then put the 0 into the ID_OUT_PAYMENT of record table .
The 0 is not the exist id of the PAYMENT table.
So when I update the ID_OUT_PAYMENT it will trigger the constraint failed.
So If I want to make my sql above run successfully.
I need to run the sql too.
db.execSQL("PRAGMA foreign_keys = OFF;");
Thanks very much for every one to reply me!!
Thanks!

Categories

Resources