trying to attach the where clause to sql statement - mysql

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)..

Related

Mysql error when select like

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 ... " ;

JPA/Hibernate query only returning one row

I am using JPA2/Hibernate5 with Java8 over MySql.
I run the following native query:
Query q = entityManager.createNativeQuery(sb.toString(), JobWithDistance.class);
q.setParameter("ids", ids);
List<JobWithDistance> jobsWD = (List<JobWithDistance>) q.getResultList();
The sql in sb returns 3 rows when I run it directly against the database with the same parameters. However, when I run the native query via Hibernate, I only get one row.
Why are the results different?
More info:
Hibernate returns 1 row:
StringBuilder sb = getFindQuery();
sb.append(" where e.id in (:ids) ");
Query q = entityManager.createNativeQuery(sb.toString(), JobWithDistance.class);
q.setParameter("ids", ids);
//Object o = q.getResultList();
List<JobWithDistance> jobsWD = q.getResultList();
and
private StringBuilder getFindQuery() {
StringBuilder sb = new StringBuilder();
sb.append(" select * ");
sb.append(" , -1 as noReviews, -1 as averageRating ");
sb.append(" , -1 AS distance ");
sb.append(" from ");
sb.append(" www.job as e ");
sb.append(" inner join www.person_job as pj on e.id = pj.JOB_ID ");
sb.append(" inner join www.person as p on pj.PER_ID = p.id ");
sb.append(" left join www.rating_job rp ON e.id = rp.JOB_ID ");
sb.append(" left join www.rating r ON rp.RAT_ID = r.id ");
return sb;
}
The following SQl when run against the database, returns 3 rows:
select * , -1 as noReviews, -1 as averageRating , -1 AS distance from www.job as e inner join www.person_job as pj on e.id = pj.JOB_ID inner join www.person as p on pj.PER_ID = p.id left join www.rating_job rp ON e.id = rp.JOB_ID left join www.rating r ON rp.RAT_ID = r.id where e.id in (65, 66, 64)
Thanks
SOLUTION:
#Override
public List<Job> findById(String ids) {
String[] args = ids.split(",");
Set<String> idSet = new HashSet<String>(Arrays.asList(args));
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Job> query = builder.createQuery(Job.class);
Root<Job> post = query.from(Job.class);
query.select(post).where(post.get("id").in(idSet)); // or pass a tag collection to `in` method
TypedQuery<Job> typedQuery = entityManager.createQuery(query);
List<Job> results = typedQuery.getResultList();
return results;
}

Comparing two queries while executing

$query=mysql_query("SELECTcom_jobcard.job_card_num,process.process_name,employee.emp_name,employee.emp_code ,SUM(worked_qty) FROMcom_jobcard
INNER JOIN timer_completed ON timer_completed.job_card_id = com_jobcard.id
INNER JOIN process ON process.id = timer_completed.process_id
INNER JOIN employee ON employee.id = timer_completed.employee_id
AND job_card_id = ( SELECT id FROM com_jobcard WHERE job_card_num = 'JCID-1271742')
GROUP BY process.process_name,employee.emp_name ");
$query1 = mysql_query("SELECT com_jobcard.job_card_num,process.process_name,employee.emp_name,employee.emp_code,SUM(qc.rework_qty),qc.report_date,qc.id FROM qc
INNER JOIN com_jobcard ON qc.job_card_id = com_jobcard.id
INNER JOIN process ON process.id = qc.process_id
INNER JOIN qc_employees ON qc_employees.qc_id = qc.id
INNER JOIN employee ON employee.id = qc_employees.employee_id
AND qc_employees.qc_id = (SELECT qc.id
FROM qc
INNER JOIN com_jobcard ON qc.job_card_id = com_jobcard.id
AND com_jobcard.job_card_num = 'JCID-1271742')
GROUP BY process.process_name,employee.emp_name");
while ($row = mysql_fetch_array($query)) {
$row1 = mysql_fetch_array($query1);
if( ($row[1] == $row1[1]) && ($row[3] == $row1[3] ))
{
echo $row1[0] .$row1[1] .$row1[2] .$row1[3] .$row1[4];
}
}
Dear friends I am executing 2 queries simultaneously but I would like to compare both the result sets when $row[1] == $row1[1]) && ($row[3] == $row1[3] the condition is satisfied then it has to return the result but as if now it returns nothing could any one suggest me how to compare the result set of both the queries , Instead of using IF I have also used While statement , though I didn't recieve the result .
Please help me!
Thank you!
Use it like this
$row1 = mysql_fetch_array($query1);
while ($row = mysql_fetch_array($query)) {
while($row1) {
if( ($row['process_name'] == $row1['process_name']) && ($row['emp_name'] == $row1['emp_name'] ))
{
echo $row1['job_card_num'] .$row1['process_name'] .$row1['emp_name'] .$row1['emp_code'] .$row1['sum_qty'];
}
}
}
Because you have used $row[1] $row1[1] which has no value.
I ahev used alias vakue for SUM(qc.rework_qty) in your query as sum_qty

How to increase Performance issue with ActiveRecord and database

I am using Rails 3.2.13, Mysql, Sql to filter records. Search is working perfect. But it is taking more time (more than a minute) to return result.
I cannot use eager loading here because raw sql query with join is used and i cannot use cache because our records will change frequently as per filters. FYI i have already used indexes in tables.
Any solution would be appreciated. Thanks in advance.
My Controller:
class ProjectReportsController < ApplicationController
def index
#results = ProjectCustomValueSearch.new(params[:teams], params[:contract_types], params[:retainer_ends], params[:retainer_ends_date], params[:status]).search
end
end
My Model:
class ProjectCustomValueSearch
attr_reader :teams, :contract_types, :retainer_ends, :retainer_ends_date, :status
def initialize(teams, contract_types, retainer_ends, retainer_ends_date, status)
#teams = teams
#contract_types = contract_types
#retainer_ends = retainer_ends
#retainer_ends_date = retainer_ends_date
#status = status
end
def search
#add status filter condition
status_query = (#status=='Both' || #status.blank?) ? " p.status = 1 OR p.status = 5" : " p.status = #{ActiveRecord::Base.sanitize(#status)}"
other_conditions = ''
#add team filter condition
if (#teams!='DM' && #teams!='Web')
other_conditions += " AND cv_team.value #{all_none_condition(#teams, 'cv_team.value')}"
elsif (#teams=="DM" || #teams=="Web")
other_conditions += " AND #{dm_or_web_condition(#teams)}"
end
#add cv_contract_type filter condition
other_conditions += " AND cv_contract_type.value #{all_none_condition(#contract_types, 'cv_contract_type.value')}"
#add cv_retainer_end value and cv_retainer_end date filter conditions
other_conditions += " AND cv_retainer_end.value #{before_after_condition(#retainer_ends_date, #retainer_ends)}" if #retainer_ends_date.present?
#Sql query is something like this:
sql = <<-sql
select p.id, p.name as project_name,
u_web_pm.firstname as web_pm_firstname,
u_web_pm.lastname as web_pm_lastname,
concat(u_marketing_pm.firstname, ' ', u_marketing_pm.lastname) as marketing_pm_value,
u_client_contact.firstname as client_contact_firstname,
u_client_contact.lastname as client_contact_lastname,
FORMAT(Round(cv_monthly_retainer.value, 0), 0) as monthly_retainer_value,
FORMAT(Round(cv_project_budget.value, 0), 0) as project_budget_value,
cv_rates.value as rates_value,
cv_retainer_start.value as retainer_start_value,
cv_retainer_end.value as retainer_end_value,
cv_contract_type.value as contract_type_value,
cv_team.value as team_value,
cv_discount.value as discount_value,
cv_account_rep.value as account_rep_value,
FORMAT(Round(cv_project_budget.value / 150, 0), 0) as budget_project,
FORMAT(Round(cv_monthly_retainer.value / 150, 0), 0) as budget_retainer,
FORMAT(Round(sum(time_entry.hours), 0), 0) as total_hours
from projects p
#Web PM
left join custom_values as cv_web_pm on p.id = cv_web_pm.customized_id and cv_web_pm.custom_field_id=4
left join users as u_web_pm on cv_web_pm.value = u_web_pm.id
#Marketing PM
left join custom_values as cv_marketing_pm on p.id = cv_marketing_pm.customized_id and cv_marketing_pm.custom_field_id=5
left join users as u_marketing_pm on cv_marketing_pm.value = u_marketing_pm.id
#Client Contact
left join custom_values as cv_client_contact on p.id = cv_client_contact.customized_id and cv_client_contact.custom_field_id=6
left join users as u_client_contact on cv_client_contact.value = u_client_contact.id
#Monthly Retainer
left join custom_values as cv_monthly_retainer on p.id = cv_monthly_retainer.customized_id and cv_monthly_retainer.custom_field_id=7
#Project Budget
left join custom_values as cv_project_budget on p.id = cv_project_budget.customized_id and cv_project_budget.custom_field_id=8
#Rates
left join custom_values as cv_rates on p.id = cv_rates.customized_id and cv_rates.custom_field_id=9
#Retainer Start
left join custom_values as cv_retainer_start on p.id = cv_retainer_start.customized_id and cv_retainer_start.custom_field_id=10
#Retainer End
left join custom_values as cv_retainer_end on p.id = cv_retainer_end.customized_id and cv_retainer_end.custom_field_id=11
#Contract Type
left join custom_values as cv_contract_type on p.id = cv_contract_type.customized_id and cv_contract_type.custom_field_id=12
#Team
left join custom_values as cv_team on p.id = cv_team.customized_id and cv_team.custom_field_id=13
#additional filters
where #{status_query}
#{other_conditions}
Group BY p.id
order by p.name ASC
sql
ActiveRecord::Base.connection.execute(sql)
end
private
def all_none_condition(str, field='')
case str
when 'All'
return " = '' or #{field} <> '' "
when 'Any'
return " <> '' "
when 'None'
return " = '' "
else
return " = #{ActiveRecord::Base.sanitize(str)}"
end
end
def dm_or_web_condition(str)
case str
when 'DM'
return " (cv_team.value='DM 1' OR cv_team.value='DM 2') "
when 'Web'
return " (cv_team.value='Web 1' OR cv_team.value='Web 2') "
end
end
def before_after_condition(date, condition)
case condition
when 'Before'
return " < #{ActiveRecord::Base.sanitize(date)} and cv_retainer_end.value <> ''"
when 'After'
return " > #{ActiveRecord::Base.sanitize(date)} and cv_retainer_end.value <> ''"
end
end
end

CASE Statement in where clause in mysql

I'm trying to fetch data from table where I'm using a CASE condition in the WHERE clause and currently I'm using following query:-
$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ",
implode(", ", $aColumns))." FROM (select CASE when r.agent_id=24
THEN r.Unit ELSE '--' END AS MyUnit,
CASE when r.agent_id=24 THEN r.landlord_name ELSE '--' END AS landlord_name_new,
r.*,l.loc_name as location,sl.sub_sub_loc as sub_location,
c.category as category,CONCAT(u.first_name, ' ', u.last_name) As agent
from crm_sales r
LEFT JOIN crm_location l ON r.area_location_id=l.loc_id
LEFT JOIN crm_subloc sl ON sl.sub_loc_id = r.sub_area_location_id
LEFT JOIN crm_category c on c.id = r.category_id
LEFT JOIN crm_users u on u.id=r.agent_id
where r.is_active=1 AND r.is_archive=0
AND CASE agent_id WHEN r.agent_id!=24 then r.status=2 else 1=1
group by r.ref) sel
$sWhere
$sOrder
$sLimit
";
Now I want to add one more condition, something like this.
IF(r.agent_id != 24) THEN WHERE r.status=2
EDITED: ADD CASE which i want but error
Fix the case/when clause in your WHERE clause to...
AND CASE WHEN r.agent_id != 24
then r.status = 2
else 1 = 1 end