pls help to solve below mentioned error :
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 'r.Username LIKE '%usernameanswer%' and r.Createtime > NOW() - INTERVAL 30 SECOND
Code
public List <CorrekctanswerModel> answerlist(String usernameanswer) throws Exception {
log.info("daomimpl" + usernameanswer);
List<CorrekctanswerModel> answerarray = new ArrayList<CorrekctanswerModel>();
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = " select s.NAME as Subject, d.value as variant, r.Username, r.UserAnswer, r.Correctanswer, r.Createtime from resultlog r " +
" inner join test_table t on t.ID = r.QuestionId " +
" inner join subject s on s.ID= t.SUBJECT " +
" inner join dictionary d on d.ID = t.Variant" +
"where r.Username LIKE '%usernameanswer%' and r.Createtime > NOW() - INTERVAL 30 SECOND " ;
try {
c = DbHelper.getConnection();
if (c != null) {
ps = c.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
CorrekctanswerModel rep = new CorrekctanswerModel();
rep.setSubject(rs.getString("Subject"));
rep.setVariant(rs.getString("variant"));
rep.setUsername(rs.getString("Username"));
rep.setUseranswer(rs.getString("UserAnswer"));
rep.setCorrekctanswer(rs.getString("Correctanswer"));
rep.setCreatedate(rs.getDate("Createtime"));
answerarray.add(rep);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtility.close(c, ps, rs);
}
return answerarray;
}
I'm going to add this as an answer in case someone stumbles upon this question...
In your code, SQL is generated with these lines:
String sql = " select <fields> from resultlog r " +
" inner join test_table t on t.ID = r.QuestionId " +
" inner join subject s on s.ID= t.SUBJECT " +
" inner join dictionary d on d.ID = t.Variant" +
"where r.Username LIKE '%usernameanswer%' and ... " ;
There should be a white space before where OR a white space after t.Variant. In its current form, the query will do this:
... inner join dictionary d on d.ID = t.Variantwhere r.Username ...
Adding a space before where like so:
String sql = " select <fields> from resultlog r " +
" inner join test_table t on t.ID = r.QuestionId " +
" inner join subject s on s.ID= t.SUBJECT " +
" inner join dictionary d on d.ID = t.Variant" +
" where r.Username LIKE '%usernameanswer%' and ... " ;
will result in your query written like this:
... inner join dictionary d on d.ID = t.Variant where r.Username ...
Also, it looks like usernameanswer is a variable. If it is, the where clause will look like this:
" where r.Username LIKE '%" + usernameanswer + "%' and ... " ;
Related
I have mysql query for joining 3 tables, how can i convert this into JPA with pagination supported.
query :
SELECT promotion.name,
promotion.promotion_type,
promotion.start_date,
promotion.end_date,
promotion_history.`count` AS order_count,
Count(user_promotion_history.promotionid) AS user_count
FROM promotion
INNER JOIN user_promotion_history
ON promotion.promotionid = user_promotion_history.promotionid
INNER JOIN promotion_history
ON promotion.promotionid = promotion_history.promotionid
WHERE promotion.status = "created"
GROUP BY promotion.name,
promotion.promotionid,
promotion.promotion_type,
promotion.start_date,
promotion.end_date,
order_count;
I have created all entity and repository classes and used native query,
#Query(value = "select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date" +
" promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count" +
" from promotion" +
" inner JOIN user_promotion_history on" +
" promotion.promotionid = user_promotion_history.promotionid" +
" inner join promotion_history on" +
" promotion.promotionid = promotion_history.promotionid" +
" where promotion.status = :status" +
" group by" +
" promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count",
nativeQuery = true)
List<Object[]> findByStatus(#Param("status")PromotionStatus status);
but getting an error like this.
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 '.count as order_count, count(user_promotion_history.promotionid)
as user_count f' at line 1
For pagination i have used Pageable parameter.
#Query(value = "select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date," +
" promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count" +
" from promotion" +
" join user_promotion_history on" +
" promotion.promotionid = user_promotion_history.promotionid" +
" join promotion_history on" +
" promotion.promotionid = promotion_history.promotionid" +
" where promotion.status = ?1" +
" group by" +
" promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count \n-- #pageable\n",
nativeQuery = true)
List findByStatus(String status, Pageable pageable);
when i see query looks like this,
Hibernate: select promotion.name, promotion.promotion_type, promotion.start_date, promotion.end_date, promotion_history.count as order_count, count(user_promotion_history.promotionid) as user_count from promotion join user_promotion_history on promotion.promotionid = user_promotion_history.promotionid join promotion_history on promotion.promotionid = promotion_history.promotionid where promotion.status = ? group by promotion.name, promotion.promotionid, promotion.promotion_type, promotion.start_date,promotion.end_date, order_count
-- #pageable
order by join.user_count desc limit ?
error says : org.hibernate.engine.jdbc.spi.SqlExceptionHelper Unknown column 'join.user_count' in 'order clause'
somewhere "join." is getting added in order by clause.
I'm trying to make a temporary table from a query with another column which is calculated in the query...
Here is my query:
asprintf(&query,
"CREATE TEMPORARY TABLE IF NOT EXISTS task_tab (PRIMARY KEY(event_id))"
"SELECT V.id as event_id, V.event_time, D.user, V.location FROM device D "
"JOIN device_service DS ON D.id = DS.device_id "
"JOIN services S ON DS.service_id = S.id "
"JOIN device_event V ON D.id = V.device_id "
"WHERE V.store = 'event_box' AND S.options = 'box_length' AND (S.flags & 1 = 1)"
"AND V.event_time + (IF(S.value IS NULL, %d, S.value) * 86400000) <= %llu"
"AND D.id IN ( SELECT D.id FROM device D "
"JOIN device_service DS ON D.id = DS.device_id "
"JOIN services S ON DS.service_id = S.id "
"WHERE S.action = 'delete' AND (S.flags & 1 = 1)",
app_config->def_expire, current_epoch_ms);
I'd like to create a column 'expire_time' in this temporary table, and store the result of this part of the query in that column:
V.event_time + (IF(S.value IS NULL, %d, S.value) * 86400000)
Any ideas?
Add
V.event_time + (IF(S.value IS NULL, %d, S.value) * 86400000) AS `expire_time`
to your SELECT filed list
I am getting the error
[57, 57] An identification variable must be defined for a JOIN expression
when trying to run this query
public String searchString = "test";
public List<Appointment> appointmentRangeSearch(Date startdatetime, Date endDate) {
Query q = em.createQuery("SELECT u FROM Appointment U INNER JOIN Users_appointment "
+ "ON u.userid = users_appointment.userid"
+ " WHERE u.startDatetime BETWEEN :date1 AND :date2 "
+ "AND u.ATTENDEES_USER_NAME LIKE :search");
//Query q = em.createQuery("SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN :date1 AND :date2");
q.setParameter("search", "%" + searchString + "%");
q.setParameter("date1", startdatetime, TemporalType.TIMESTAMP);
q.setParameter("date2", endDate, TemporalType.TIMESTAMP);
return q.getResultList();
}
What is causing this? How can it be fixed?
Maybe, beacuse you have different table names:
INNER JOIN Users_appointment
AND
users_appointment.userid
Don't see anything wrong... try making U lower case and use
SELECT u.* FROM Appointment u....
em.createQuery("SELECT u.* FROM Appointment u INNER JOIN Users_appointment "
+ "ON u.userid = users_appointment.userid"
+ " WHERE u.startDatetime BETWEEN :date1 AND :date2 "
+ "AND u.ATTENDEES_USER_NAME LIKE :search");
I am joining product and cart table to calculate for the total price for each cart. Here is my sql statement:
String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity, p.productPrice * c.quantity as new_unit_price, SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " WHERE c.custName = '" + custName + "'";
I derived a column named new_unit_price by multiplying the quantity from cart table and product price from product table. Then I want to use the derived column which is new_unit_price to sum up the price of all item in the cart. I get the data from the column in database by:
double subItemTotal = rs.getDouble("new_unit_price");
double totalPrice = rs.getDouble("totalPrice");
My new_unit_price works. But unfortunately, my sum does not works. It's still 0. Does anybody know how can I sum up the value from derived column? Thanks in advance.
To use the SUM() function, you'll need to do a GROUP BY at the end of your statement.
This should get your overall cart total:
String sql = "SELECT c.custname "
+ ", SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " AND c.custName = '" + custName + "'"
+ " GROUP BY c.custname;"
Also, I changed the WHERE to an AND so it is evaluated earlier and should make the query faster.
If you want the new_unit_price and the cart total in the same query, you have to go back into the tables again to get that data. Something like this should work:
String sql = "SELECT p.productID, p.productName, p.productPrice, c.quantity "
+ ", p.productPrice * c.quantity as new_unit_price, total.totalPrice FROM "
+ "( "
+ "SELECT c.custname "
+ ", SUM(p.productPrice * c.quantity) AS totalPrice"
+ " FROM sm_product p INNER JOIN sm_cart c "
+ "ON p.productID = c.productID"
+ " AND c.custName = '" + custName + "'"
+ " GROUP BY c.custname"
+ ") AS total "
+ "INNER JOIN sm_cart c "
+ "ON total.custname=c.custname "
+ "INNER JOIN sm_product p "
+ "ON p.productID = c.productID "
HiI am trying to attach the where clause to sql statement like this
public static DataTable paymentType(string paymenttype, string ddproviders, string overdue)
{
string paymenttypestr = "";
string ddproviderstr = "";
if (paymenttype != "")
{
paymenttypestr = string.Format("AND membertomships.memberToMship_PayMethod = '{0}'", paymenttype);
}
if (ddproviders != "")
{
ddproviderstr = string.Format("AND ddproviders.ddProvider_Name = '{0}'", ddproviders);
}
if (overdue == "OverDue-Now")
{
string sql += #"WHERE memberpaysched.memberPaySched_dateDue < NOW() AND memberpaysched.memberPaySched_amountDue > memberpaysched.memberPaySched_amountPaid ";
}
string sql = string.Format(
#"SELECT members.member_Id,
members.member_Lastname As Last_name,
members.member_Firstname AS First_name,
members.member_PostCode As Post_Code,
ddaccounts.ddAccount_DdReference As dd_reference,
ddproviders.ddProvider_Name As dd_providername,
memberToMship_ChargePerPeriod As monthly_amount,
mshiptypes.mshipType_Name As Membership_type,
mshipstatustypes.mshipStatusType_Name As Status,
membertomships.memberToMship_EndDate As Expiry_Date,
membertomships.memberToMship_PayMethod As payment_method
FROM members
LEFT JOIN membertomships ON membertomships.member_Id = members.member_Id
LEFT JOIN memberpaysched ON memberpaysched.memberPaySched_memberId = members.member_Id
LEFT OUTER JOIN ddaccounts ON ddaccounts.member_Id = members.member_Id
LEFT OUTER JOIN ddproviders ON ddaccounts.ddProvider_Id=ddproviders.ddProvider_Id
LEFT JOIN mshipstatustypes ON mshipstatustypes.mshipStatusType_Id = membertomships.mshipStatusType_Id
LEFT JOIN mshipoptions ON mshipoptions.mshipOption_Id = membertomships.mshipOption_Id
LEFT JOIN mshiptypes ON mshiptypes.mshipType_Id = mshipoptions.mshipType_Id
WHERE members.member_Active LIKE 'y%'
AND mshipoptions.mshipOption_Period = 'month'
AND (mshipstatustypes.mshipStatusType_Id <> 5)
{0}
{1}
ORDER BY members.member_Lastname",
paymenttypestr, ddproviderstr);
return getdata(sql,mf);
}
but it was giving error at this line like ";" this symbol is needed;
string sql += #"WHERE memberpaysched.memberPaySched_dateDue < NOW() AND memberpaysched.memberPaySched_amountDue > memberpaysched.memberPaySched_amountPaid ";
I want to add this where clause if overdue == "overdue-now"
how can i add this where clause according to condition
would any one help on this ....
Modified Query : string sql += #"memberpaysched.memberPaySched_dateDue < NOW() AND memberpaysched.memberPaySched_amountDue > memberpaysched.memberPaySched_amountPaid";
still it was showing this error
"Invalid EXPRESSION TERM +="
On 1st glance you have 2 where clauses. Change the one you're adding to an AND and see what happens.
So if overdue == "OverDue-Now" you are declaring a string of sql and +=ing it? But then you overwrite the string you thought you just created.
I think this is what you're trying to accomplish:
if (overdue == "OverDue-Now")
{
string isoverduestr = #"AND memberpaysched.memberPaySched_dateDue < NOW() AND memberpaysched.memberPaySched_amountDue > memberpaysched.memberPaySched_amountPaid ";
}
else
{
string isoverduestr = #"";
}
string sql = string.Format(
#"SELECT members.member_Id,
members.member_Lastname As Last_name,
members.member_Firstname AS First_name,
members.member_PostCode As Post_Code,
ddaccounts.ddAccount_DdReference As dd_reference,
ddproviders.ddProvider_Name As dd_providername,
memberToMship_ChargePerPeriod As monthly_amount,
mshiptypes.mshipType_Name As Membership_type,
mshipstatustypes.mshipStatusType_Name As Status,
membertomships.memberToMship_EndDate As Expiry_Date,
membertomships.memberToMship_PayMethod As payment_method
FROM members
LEFT JOIN membertomships ON membertomships.member_Id = members.member_Id
LEFT JOIN memberpaysched ON memberpaysched.memberPaySched_memberId = members.member_Id
LEFT OUTER JOIN ddaccounts ON ddaccounts.member_Id = members.member_Id
LEFT OUTER JOIN ddproviders ON ddaccounts.ddProvider_Id=ddproviders.ddProvider_Id
LEFT JOIN mshipstatustypes ON mshipstatustypes.mshipStatusType_Id = membertomships.mshipStatusType_Id
LEFT JOIN mshipoptions ON mshipoptions.mshipOption_Id = membertomships.mshipOption_Id
LEFT JOIN mshiptypes ON mshiptypes.mshipType_Id = mshipoptions.mshipType_Id
WHERE members.member_Active LIKE 'y%'
AND mshipoptions.mshipOption_Period = 'month'
AND (mshipstatustypes.mshipStatusType_Id <> 5)
{0}
{1}
{2}
ORDER BY members.member_Lastname",
paymenttypestr, ddproviderstr, isoverduestr);
I'm no .NET expert, but I'd probably change:
if (overdue == "OverDue-Now")
{
string sql += #"WHERE memberpaysched.memberPaySched_dateDue < NOW() AND memberpaysched.memberPaySched_amountDue > memberpaysched.memberPaySched_amountPaid ";
}
to:
if (overdue == "OverDue-Now")
{
sql += #"AND memberpaysched.memberPaySched_dateDue < NOW() AND memberpaysched.memberPaySched_amountDue > memberpaysched.memberPaySched_amountPaid ";
}
(i.e. remove the string keyword, and substitute AND for WHERE)
and put it AFTER the main SQL block (i.e. where you're declaring your string sql variable)..