MySQL Deletion Query, Multiple Inner Joins - java

I want to delete an "order" from my database using the primary key, orderID. The orderID is a foreign key in orderItem, OrderItem has a foreign key in foodItem called foodItemID, foodItem has a foreign key in menu called menuID.
Below is my query:
"DELETE FROM orders, orderitem, fooditem, menu " +
"USING orders " +
"INNER JOIN orderitem " +
"WHERE orderID = " + "'" + orderID + "' " + " AND orders.orderID = orderItem.orderID " +
"INNER JOIN foodItem " +
"WHERE orderItem.foodItemID = foodItemID.foodItemID " +
"INNER JOIN Menu " +
"WHERE foodItem.menuID = menu.menuID";
I am coding in JAVAFX..
The error I receive is:
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN foodItem WHERE orderItem.foodItemID = foodItemID.foodItemID INNER JOI' at line 1

You don't join WHERE, you join ON something. So
"DELETE FROM orders, orderitem, fooditem, menu " +
"USING orders " +
"INNER JOIN orderitem " +
"ON orderID = " + "'" + orderID + "' " + " AND orders.orderID = orderItem.orderID " +
"INNER JOIN foodItem " +
"ON orderItem.foodItemID = foodItemID.foodItemID " +
"ON JOIN Menu " +
"ON foodItem.menuID = menu.menuID";
Also, this part
"ON orderID = " + "'" + orderID + "' " + "
Is a SQL Injection waiting to happen. You should use prepared statements instead. How you use them depends on what library/framework you're using to connect to the db (which you didn't specify).

Related

Duplicated records in HQL

I need to return the ID of the duplicate records from a table using HQL. I Tried:
"select pro from FichaProcedimento pro "
+ " inner join ("
+ " select pro.ficha.id, proc.id, proc.regiaoDente, proc.face "
+ " from FichaProcedimento "
+ " group by pro.ficha.id, proc.id, proc.regiaoDente, proc.face"
+ " having count(*)>1) proc "
+ " on pro.procedimento.id = proc.procedimento.id "
+ " where pro.ficha.id=? "
Error occurred:
unexpected token: ( near line 1, column 100 [select pro from br.srv.datasolution.infodata.odontologico.entity.FichaProcedimento pro inner join ( select pro.ficha.id, proc.id, proc.regiaoDente, proc.face from br.srv.datasolution.infodata.odontologico.entity.FichaProcedimento group by pro.ficha.id, proc.id, proc.regiaoDente, proc.face having count(*)>1) proc on pro.procedimento.id = proc.procedimento.id where pro.ficha.id=? ]
How to solve?
Solved with native query. Thanks! Example:
delete from Tabela
where Nome in
(select Nome from Tabela
group by Nome
having Count(Nome)>1)
and not matricula in
(select Min(Matricula) from Tabela
group by Nome
having Count(Nome)>1)

JDBC resultset not working when using aliases I receive " java.sql.SQLSyntaxErrorException: ORA-00905: missing keyword"

I wanted to execute this query, but it gave me an error without using variables but it gave me an error ORA-00905: missing keyword.
I tested the query in SQL Developer and it ran with no errors. I'm probably think it's a driver issue or a syntax issue with JDBC. But I have no idea here's the code:
public List<ReimbBean> getAllReimb() {
String sql = "select reim.reimb_id, reim.reimb_amount,"
+ "reim.reimb_submitted, reim.reimb_resolved, "
+ "CONCAT(CONCAT(u.user_first_name,' '),"
+ " u.user_last_name) AS \"REIMB_AUTHOR\", "
+ "reim.REIMB_RESCRIPTION, rst.REIMB_STATUS, "
+ "rtype.REIMB_TYPE, CONCAT(CONCAT(urs.user_first_name,' '), "
+ "urs.user_last_name) AS \"REIMB_RESOLVER\""
+ "FROM ERS_REIMBURSTMENT reim"
+ "LEFT JOIN ERS_USERS u"
+ "ON u.ERS_USERS_ID = reim.REIMB_AUTHOR"
+ "LEFT JOIN ERS_REIMBURSTMENT_STATUS rst"
+ "ON rst.REIMB_STATUS_ID = reim.REIMB_STATUS_ID"
+ "LEFT JOIN ERS_REIMBURSTMENT_TYPE rtype"
+ "ON rtype.reimb_type_id = reim.REIMB_TYPE_ID"
+ "LEFT JOIN ERS_USERS urs"
+ "ON urs.ERS_USERS_ID = reim.REIMB_RESOLVER"
+ "ORDER BY reim.reimb_id";
List<ReimbBean> reimbAllList = new ArrayList<>();
ReimbBean reimb = new ReimbBean();
try {
PreparedStatement preparedStatement = conn6.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()){
reimb.setReimbAmount(rs.getDouble("reimb_Amount"));
reimb.setReimbDescript(rs.getString("reimb_Description"));
reimb.setReimbSubmitted(rs.getTimestamp("reimb_Submitted"));
reimb.setReimbAuthor(rs.getInt("reimb_Author"));
reimb.setReimbResolved(rs.getTimestamp("reimb_Resolved"));
reimb.setReimbResolver(rs.getInt("reimb_Resolver"));
reimb.setReimbStatusID(rs.getInt("reimb_Status_ID"));
reimb.setReimbTypeID(rs.getInt("reimb_Type_ID"));
reimbAllList.add(reimb);
}
I read online that the preapareStatement is unable to bind objects only variables, so the alternative was to define them explicitly, so I created a part for declarations and substituted the fields with String variables, but the error continues to persist.
You are missing whitespaces at the end of a lot of those strings:
String sql = "select reim.reimb_id, reim.reimb_amount,"
+ "reim.reimb_submitted, reim.reimb_resolved, "
+ "CONCAT(CONCAT(u.user_first_name,' '),"
+ " u.user_last_name) AS \"REIMB_AUTHOR\", "
+ "reim.REIMB_RESCRIPTION, rst.REIMB_STATUS, "
+ "rtype.REIMB_TYPE, CONCAT(CONCAT(urs.user_first_name,' '), "
+ "urs.user_last_name) AS \"REIMB_RESOLVER\" " // Here
+ "FROM ERS_REIMBURSTMENT reim " // and here
+ "LEFT JOIN ERS_USERS u " // and here
+ "ON u.ERS_USERS_ID = reim.REIMB_AUTHOR " // and here
+ "LEFT JOIN ERS_REIMBURSTMENT_STATUS rst " // and here
+ "ON rst.REIMB_STATUS_ID = reim.REIMB_STATUS_ID " // and here
+ "LEFT JOIN ERS_REIMBURSTMENT_TYPE rtype " // and here
+ "ON rtype.reimb_type_id = reim.REIMB_TYPE_ID " // and here
+ "LEFT JOIN ERS_USERS urs " // and here
+ "ON urs.ERS_USERS_ID = reim.REIMB_RESOLVER " // and here
+ "ORDER BY reim.reimb_id";

JPA Query to handle NULL Value parameters

i want to select rows from a table in JPA, my query paramter could be null.
So if it is null i want to consider all values for that attribute in that table.
Here is my code :
#Query("SELECT art FROM ArtWork art INNER JOIN art.subjects subject "
+ "INNER JOIN art.styles style "
+ "INNER JOIN art.collections collection "
+ "INNER JOIN art.priceBuckets priceBucket "
+ " WHERE ((subject.title) in (:subjectList) "
+ "AND (style.title) in (:styleList)"
+ "AND (collection.title) in (:collectionList)"
+ "AND (priceBucket.title) in (:priceBucketRangeList)"
+ "AND (art.medium is NULL OR art.medium = :medium)"
+ "AND (art.orientation) LIKE:orientation)"
+ ")")
In the code if :medium is null then i want it search on all mediums in the table
Thanks

SQL Query deleting duplicate records not working

Good day. I have a query in my Java code that deletes duplicate rows in a table. Initially it worked and for a while i didn't touch the project. But on running the file a few days ago, my code was throwing exceptions. This is my code:
String query = "DELETE error_log FROM error_log INNER JOIN "
+ "(SELECT min(id) minid, service_source, channel,transaction_type, provider_name, pido_account, beneficiary_id, error_description, error_date FROM error_log "
+ "GROUP BY service_source, channel, transaction_type, provider_name, pido_account, beneficiary_id, error_description, error_date "
+ "HAVING COUNT(1) > 1 AS duplicates ON "
+ "(duplicates.service_source = error_log.service_source AND duplicates.channel = error_log.channel "
+ "AND duplicates.transaction_type = error_log.transaction_type AND duplicates.provider_name = error_log.provider_name "
+ "AND duplicates.pido_account = error_log.pido_account AND duplicates.beneficiary_id = error_log.beneficiary_id "
+ "AND duplicates.error_description = error_log.error_description AND duplicates.error_date = error_log.error_date "
+ "AND duplicates.minid <> error_log.id"
+ ")"
+ ")";
int deploy = duplicate.executeUpdate(query);
I get this afterwards:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS duplicates ON (duplicates.service_source = error_log.service_source AND dupli' at line 1.
How do i correct this and have the duplicates deleted from the table?
You have a missing ) on line + "HAVING COUNT(1) > 1 AS duplicates ON " and have an extra ) at the end.
String query = "DELETE error_log FROM error_log INNER JOIN "
+ "(SELECT min(id) minid, service_source, channel,transaction_type, provider_name, pido_account, beneficiary_id, error_description, error_date FROM error_log "
+ "GROUP BY service_source, channel, transaction_type, provider_name, pido_account, beneficiary_id, error_description, error_date "
+ "HAVING COUNT(1) > 1 ) AS duplicates ON "
+ "(duplicates.service_source = error_log.service_source AND duplicates.channel = error_log.channel "
+ "AND duplicates.transaction_type = error_log.transaction_type AND duplicates.provider_name = error_log.provider_name "
+ "AND duplicates.pido_account = error_log.pido_account AND duplicates.beneficiary_id = error_log.beneficiary_id "
+ "AND duplicates.error_description = error_log.error_description AND duplicates.error_date = error_log.error_date "
+ "AND duplicates.minid <> error_log.id"
+ ")";
int deploy = duplicate.executeUpdate(query);
If you haven't made any changes and it stopped working, 1) are you sure you tested this code? and 2) has anyone else made any changes without your knowledge?

SQL: ten first contacts that I have received message from or sent to along with their latest sent message and time

I have a follow up to complicated mysql question that I recently asked: Show the ten first contacts that I have recieved message
Now I know that it is missing something, my last question was:
I want to create Sql statement that
show the ten first contacts that I
have recieved message from along with
their latest sent message and time.
The table columns is messageId,
message, fromProfileId, toProfileId,
timeStamp and table is called
messages. The database is Mysql and
Java is the language. But I want this
to happen in one single sql statement.
What's missing is that I want to show the message I've sent also, but it should be grouped with the messages that I've recieved from the user I've sent to:
ten first contacts that I have
received message from or sent to along
with their latest sent message and
time.
Little complicated to understand? Ok. think like this. the quoted first sql statement above only show messages that I reveived from. but what if I send a message? That message will never show up.
This is my code, but I failed to succed(look at where I marked the comment):
"SELECT M2.messageProfileId, profiles.profileMiniature, profiles.firstName, profiles.lastName, profiles.timeFormat, lastMessages.message, lastMessages.timeStamp " +
"FROM (" +
" SELECT IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) AS messageProfileId, " +
" max(M1.timeStamp) AS lastMessageTime " +
" FROM messages AS M1 " +
" WHERE M1.toProfileId = ? " +
" OR M1.fromProfileId = ? " +
" GROUP BY IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) " +
" ORDER BY max(M1.timeStamp) DESC " +
" LIMIT 10 " +
" ) AS M2 " +
"INNER JOIN messages AS lastMessages " +
"ON (" +
" lastMessages.timeStamp = M2.lastMessageTime " +
"AND lastMessages.fromProfileId = M2.messageProfileId" +//This to be like the if statements above, but how?
" )" +
"INNER JOIN profiles " +
"ON M2.messageProfileId = profiles.profileId ";
UPDATE:
All question marks in the above code will be replaced with a a same id, for example 27.
UPDATE:
You just have to solve one line now. Look at the commented line above. I dont know how to make if statement in where clause?
Ok figured it out myself
"SELECT M2.messageProfileId, profiles.profileMiniature, profiles.firstName, profiles.lastName, profiles.timeFormat, lastMessages.message, lastMessages.timeStamp " +
"FROM (" +
" SELECT IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) AS messageProfileId, " +
" max(M1.timeStamp) AS lastMessageTime " +
" FROM messages AS M1 " +
" WHERE (M1.toProfileId = ? " +
" OR M1.fromProfileId = ?) " +
" GROUP BY IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) " +
" ORDER BY max(M1.timeStamp) DESC " +
" LIMIT 10 " +
" ) AS M2 " +
"INNER JOIN messages AS lastMessages " +
"ON (" +
" lastMessages.timeStamp = M2.lastMessageTime " +
"AND (" +
" lastMessages.fromProfileId = M2.messageProfileId " +
"OR lastMessages.toProfileId = M2.messageProfileId " +
" )" +
" )" +
"INNER JOIN profiles " +
"ON M2.messageProfileId = profiles.profileId ";

Categories