SQL search not running - mysql

Hi guys i have the following search command
public List<User> advancedSearch(String searchString, String criteria, String ordering) {
Query q = em.createQuery("SELECT u FROM USERS U WHERE u.username LIKE :search ORDER BY u.username, order");
q.setParameter("search", "%" + searchString + "%");
q.setParameter("order", "%" + ordering + "%");
return q.getResultList();
}
i get the values of the searhString, criteria and ordering from the U.I, the aim is to produce a query that is fully customisable, however currently i am having issues with the ordering, how can i use the value from the U.I. (order) in the query, as currently it is not running like this

i guess you mixed between the column and the table with big letter U
you should use this
Query q = em.createQuery("SELECT u FROM USERS U WHERE U.username LIKE :search ORDER BY U.username");
U.username and not u.username
EDIT:
Query q = em.createQuery("SELECT u FROM USERS U WHERE u.username LIKE :search ORDER BY u.username " + ordering + ");
and remove that line
q.setParameter("order", "%" + ordering + "%");
you cant set DESC and ASC as parameters

Related

How to get distinct results using GORM

In Go, I write a query that gives me all data but I just want to data where products.id and clients.id are distinct.
What is the simile query I can write?
res := find.Model(&domain.Clients{}).
Select ("products.id product_id, products.name product_name,"+
" clients.id id, clients.name name, clients.logo, clients.address, "+
"clients.business_id, clients.num_of_employee, clients.email, clients.sns_link, clients.phone").
Joins("LEFT JOIN company_interests ON company_interests.client_id = clients.id").
Joins("LEFT JOIN products ON products.id = company_interests.product_id").
Where("products.id = ? ", productId).Find(&resp)
In Go when i write "Select Distinct" then rest query , it is not valid in go. So, i got an idea to write the query using "group by". In Go "group by" syntax can be used by "GROUP" syntax . So, finally bellow query works fine for me.
res := find.Model(&domain.Clients{}).
Select ("products.id product_id, products.name product_name,"+
" clients.id id, clients.name name, clients.logo, clients.address, "+
"clients.business_id, clients.num_of_employee, clients.email, clients.sns_link, clients.phone").
Joins("LEFT JOIN company_interests ON company_interests.client_id = clients.id").
Joins("LEFT JOIN products ON products.id = company_interests.product_id").
Where("products.id = ? ", productId).
Group("company_interests.client_id, company_interests.product_id" ).Find(&resp)

Ordering mysql query results by location

I've a search bar to search for other users by their name or username, and that's easy to do, but what I'm trying to do is that in case more that one user have the same name that you're searching for I want to show first the closest one to you, so that first will appear the users with that name who are in the same city as u, then the same country, and then the rest of the world, I'am able to achieve the required result with multiple queries, but is it achievable with one query?
NOTE: the user table that I'm using for the search contains Username, FName, LName, CountryCode, CityID.
these are the queries I'm using now:
Select user.USERNAME, AVG(userrating.RATING) as Avg_Rating
from user LEFT JOIN userrating on user.USERNAME = userrating.USERNAME
WHERE CONCAT (user.FNAME, " ", user.LNAME) like '%Searched Name%' and user.CITYID = User's_City_ID
GROUP by user.USERNAME
ORDER by Avg_Rating
then I use the same query but for the country of the user and excluding the previously used city:
Select user.USERNAME, AVG(userrating.RATING) as Avg_Rating
from user LEFT JOIN userrating on user.USERNAME = userrating.USERNAME
WHERE CONCAT (user.FNAME, " ", user.LNAME) like '%Searched Name%' and user.CountryCode = User's_Country_Code and not user.CITYID = User's_City_ID
GROUP by user.USERNAME
ORDER by Avg_Rating
and then the same but excluding the whole country that I used in the prev. query:
Select user.USERNAME, AVG(userrating.RATING) as Avg_Rating
from user LEFT JOIN userrating on user.USERNAME = userrating.USERNAME
WHERE CONCAT (user.FNAME, " ", user.LNAME) like '%Searched Name%' and not user.CountryCode = User's_Country_Code
GROUP by user.USERNAME
ORDER by Avg_Rating
and then I'm combining the results of the three queries.
Starting from your current query (called « other » in the below SQL), you want to JOIN on the record that corresponds to the current user (called « me ») and then use a special ORDER BY clause to show the closest matching records first, using a CASE construct.
This assumes that « username » can be used to uniquely identify the current user.
SELECT
other.username
FROM userrating other
INNER JOIN userrating me on me.username = 'bar'
WHERE
CONCAT (other.FNAME, " ", other.LNAME) like '%Searched Name%'
ORDER BY
CASE
WHEN other.cityid = me.cityid THEN 0
WHEN other.countryid = me.countryid THEN 1
ELSE 2
END,
other.username
You need to replace 'bar' with current username.
It's difficult to do this exactly with one query, but you can do something like this:
SELECT * FROM users WHERE username LIKE '%searchkey%' OR fname LIKE '%searchkey%' OR lname LIKE '%searchkey%' OR countryid LIKE '%searchkey%' OR cityid LIKE '%searchkey%'
Here you can read more about the LIKE Operator.

mysql group concat unknow column error

I am trying to search for query on first name and last name field
here is my query
SELECT d.title, GROUP_CONCAT(u.firstName,' ',u.lastName) as fullname
FROM DEALS d
left JOIN USER u ON u.idUser = d.userId
WHERE ((d.title LIKE '%goutham%' OR d.keywords LIKE '%goutham%')
OR fullname LIKE '%goutham%') AND d.isPublic=1
But i got
Unknown column 'fullname' in 'where clause'
The immediate cause of your problem is that you can't refer to an alias defined in the SELECT clause in the WHERE clause of the same query. The solution would be to repeat the entire expression instead of using the alias. However, based on your comment, you really want to check the first name, so do just that:
SELECT
d.title,
CONCAT(u.firstName, ' ', u.lastName) AS fullname
FROM DEALS d
LEFT JOIN USER u
ON u.idUser = d.userId
WHERE
(d.title LIKE '%goutham%' OR
d.keywords LIKE '%goutham%' OR
u.firstName LIKE '%goutham%') AND d.isPublic = 1;
You cannot use a column alias in where. It has nothing to do with the rest of your query.
You don't have a GROUP BY, so I suspect GROUP_CONCAT() is not intended. Instead you want CONCAT(). You can repeat the expression in the WHERE, but I think you should look in each component:
SELECT d.title, CONCAT(u.firstName, ' ', u.lastName) as fullname
FROM DEALS d left JOIN USER
u
ON u.idUser = d.userId
WHERE (d.title LIKE '%goutham%' OR
d.keywords LIKE '%goutham%' OR
u.firstName LIKE '%goutham%' OR
u.lastName LIKE '%goutham%'
) AND
d.isPublic = 1;
If you care about performance and are looking for words, then you might want to look into MySQL's full text index capabilities.
If you still want to look on the combination, I would recommend repeating the expression:
WHERE (d.title LIKE '%goutham%' OR
d.keywords LIKE '%goutham%' OR
CONCAT(u.firstName, ' ', u.lastName) LIKE '%goutham%'
) AND
d.isPublic = 1;

[34, 105] The expression is not a valid conditional expression

Hi guys i am getting the error :
Exception Description: Syntax error parsing [SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN :date1 AND :date2 INNER JOIN Users_appointment where u.ATTENDEES_USER_NAME LIKE :search].
[34, 105] The expression is not a valid conditional expression.
when i am trying to run the query
public List<Appointment> appointmentRangeSearch(Date startdatetime, Date endDate) {
Query q = em.createQuery("SELECT u FROM Appointment U WHERE u.startDatetime BETWEEN :date1 AND :date2 INNER JOIN Users_appointment where u.ATTENDEES_USER_NAME LIKE :search");
q.setParameter("search", "%" + searchString + "%");
q.setParameter("date1", startdatetime, TemporalType.TIMESTAMP);
q.setParameter("date2", endDate, TemporalType.TIMESTAMP);
return q.getResultList();
}
the idea is that i search for a range of dates in the appointment table and then see if there is a matching username in the users_appointment table and if so output this
what is going wrong ?
thanks
Wrong SQL syntax used. Please go through the SQL syntax. You need to add a JOINING clause using ON to tell mysql how to link appointment table with users_appointment table. I assume that you have userid column in both tables.
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

Problems ordering the results of a SQL query when I have ties

My tables look like this:
qotwQuestion1a
QuestionId [primarykey]
Question
MemberId
PostDate
qotwVote1a
QuestionId [primarykey]
MemberId [primarykey]
Vote1a
qotwMember
MemberId [primarykey]
Name
Password
emailId
The Sql query below sums the number of votes for each questionId (which has a postDate between the startofweek and endofweek date) and then displays it.
$result2 = mysql_query(" SELECT * FROM qotwMember, qotwQuestion1a
WHERE qotwMember.MemberId=qotwQuestion1a.MemberId
AND PostDate>='".$startofweek."' AND PostDate<='".$endofweek."'
ORDER BY qotwQuestion1a.QuestionId DESC ");
while($row2 = mysql_fetch_array($result2))
{ //echo("testing");
$result3= mysql_query ("SELECT SUM(Vote1a) AS total FROM qotwVote1a
WHERE QuestionId='".$row2['QuestionId']."'
ORDER BY total DESC ");
while($row3 = mysql_fetch_array($result3))
{
echo $row2['Question'] . " " .$row2['Name'] . " " .$row3['total'];
}
}
This query works fine, except for the "ORDER BY total DESC". The query gives the result, but does not orders the result by "total".
But my issue is to get the questionId which has the maximum number of votes. if there is a tie between a few questionIds, i would need all of those questions.
Can someone help me with this
Best
Zeeshan
Your code is structured in such a way that you will only get one result record back every time the query runs. The SQL ORDER BY clause does not apply to the PHP code calling it.
You'll need to restructure this so that the ORDER BY clause is actually doing something.
I would replace the whole thing with just one query:
$result3= mysql_query ("
SELECT qotwQuestion1a.Question, qotwMember.Name, SUM(qotwVote1a.Vote1a) AS total
FROM qotwMember
INNER JOIN qotwQuestion1a
ON qotwMember.MemberId = qotwQuestion1a.MemberId
INNER JOIN qotwVote1a
ON qotwVote1a.QuestionId = qotwQuestion1a.QuestionId
WHERE PostDate>='".$startofweek."'
AND PostDate<='".$endofweek."'
GROUP BY qotwQuestion1a.Question, qotwMember.Name
ORDER BY total DESC
");
while($row3 = mysql_fetch_array($result3)) {
echo $row3['Question'] . " " .$row3['Name'] . " " .$row3['total'];
}
This assumes that Question and Name are unique by ID. If not, you'll probably want to break this up into two queries, using the IDs instead of names to look up information:
SELECT qotwQuestion1a.QuestionId, SUM(qotwVote1a.Vote1a) AS total
FROM qotwQuestion1a
INNER JOIN qotwVote1a
ON qotwVote1a.QuestionId = qotwQuestion1a.QuestionId
WHERE PostDate>='".$startofweek."'
AND PostDate<='".$endofweek."'
GROUP BY qotwQuestion1a.QuestionId
ORDER BY total DESC
Then look up member name and question based on the QuestionId.
Or you could make a really, really big query:
SELECT qotwQuestion1a.Question, qotwMember.Name, SubQuery.total
FROM (
SELECT qotwQuestion1a.QuestionId, SUM(qotwVote1a.Vote1a) AS total
FROM qotwQuestion1a
INNER JOIN qotwVote1a
ON qotwVote1a.QuestionId = qotwQuestion1a.QuestionId
WHERE PostDate>='".$startofweek."'
AND PostDate<='".$endofweek."'
GROUP BY qotwQuestion1a.QuestionId
) SubQuery
INNER JOIN qotwQuestion1a
ON SubQuery.QuestionId = qotwQuestion1a.QuestionId
INNER JOIN qotwMember
ON qotwMember.MemberId = qotwQuestion1a.MemberId
ORDER BY total DESC
The problem is that the second query always returns single row. You should combine both queries using the GROUP statement, something like this:
SELECT qotwQuestion1a.QuestionId, SUM(Vote1a) AS total
FROM qotwMember, qotwQuestion1a, Vote1a
WHERE qotwMember.MemberId=qotwQuestion1a.MemberId
AND qotwQuestion1a.QuestionId=Vote1a.QuestionId
AND PostDate>='".$startofweek."' AND PostDate<='".$endofweek."'
GROUP BY qotwQuestion1a.QuestionId
ORDER BY total desc;