I am creating a page which would have different field for the user to search from.
e.g. search by:
Grade: -dropdownlist1-
Student name: -dropdownlist2-
Student ID: -dropdownlist3-
Lessons: -dropdownlist4-
Year: -dropdownlist5-
How do I write the select statement for this? Each dropdownlist would need a select statement which would extract out different data from the database.
But, I want to write ONE select statement which can dynamically choose the dropdownlist options. Instead of writing many many select statement.
Lets say;
Grade: -dropdownlist1- ; default value(all)
Student name: -dropdownlist2-; default value(all)
Student ID: -dropdownlist3-; 0-100 is choosen
Lessons: -dropdownlist4-; A-C is choosen
Year: -dropdownlist5-; 2009 is choosen
It depends on the language you're using between SQL and the page. But test the dropdown for a non-generic value and then add in a where clause:
sql = "select * from people where 1 = 1";
if(dropdownlist.value != "All")
sql += "and name like '%" + dropdownlist.value + "%' ";
(watch out for SQL Injection though)
Extending to Tom's answer,
Create a view first which will contain the needed record set. Query on the view.
Related
I am starting out at Hibernate. I am at the point, where I try out SQL in HQL.
I saw a code example which I wanted to recreate, but my output ended up being different.
To use SQL in HQL, that person said, if you want to only use a couple of columns, you need to use a Map to get certain columns (So I canĀ“t simply use addEntity here).
My Student table got sId, sName, sMarks. Now I want to retrieve only the Students names (sName) and their marks (sMarks).
The Problem is, that I only get "null" as values for the names and marks whilst the object shows me the proper values:
Console Output:
Hibernate: SELECT sName,sMarks FROM student
{SNAME=Nameless fool number 1, SMARKS=65}
null : null
The Code:
NativeQuery querySQL2 = session.createNativeQuery("SELECT sName,sMarks "
+ "FROM student");
querySQL2.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List students = querySQL2.getResultList();
for (Object o : students)
{
System.out.println(o);
Map m = (Map)o;
System.out.println(m.get("sName") + " : " + m.get("sMarks"));
}
Why do I get the proper Object with Syso(o) and just null with Syso(m.get("..."))?
Thank you in advance!
Actually you already answered your question
{SNAME=Nameless fool number 1, SMARKS=65}. Hibernate convert column names to upper case.
I am working on a database that my school uses for student recruitment. I want to include an option on the parameter form used to generate a students contact information that allows the user to select whether or not to include "applied" students in that contact list. I am currently trying to do that by using a select query that pulls data based on whether or not the "IdNumber" field is null. When I run the attached SQL, it doesn't pull any data at all. Any help would be appreciated!
SELECT InterestCards.NotStudentID, InterestCards.Email, InterestCards.YearOfGraduation,
InterestCards.SourceTwoLocation, InterestCards.FirstName, InterestCards.LastName,
InterestCards.Program, InterestCards.Inactive, InterestCards.IDNumber
FROM InterestCards
WHERE (((InterestCards.Email)<>"no email")
AND ((InterestCards.YearOfGraduation) Like [Forms]![MassCommunicationTool]![GradYear] & "*")
AND ((InterestCards.SourceTwoLocation) Like [Forms]![MassCommunicationTool]![FairName] & "*")
AND ((InterestCards.Inactive)=No)
AND ((InterestCards.IDNumber)=Switch([Forms]![MassCommunicationTool]![IncludeApplied]=0,Null,[forms]![MassCommunicationTool]![IncludeApplied]=(-1),([InterestCards].[IDNumber]) Is Not Null Or ([InterestCards].[IDNumber]) Is Null))
AND ((InterestCards.HighSchool) Like [Forms]![MassCommunicationTool]![HighSchool] & "*")
AND ((InterestCards.SourceThreeType) Like [Forms]![MassCommunicationTool]![SelectTerm] & "*")
AND ((InterestCards.DateEntered) Between Nz([Forms]![MassCommunicationTool]![StartDate],#1/1/1900#) And Nz([Forms]![MassCommunicationTool]![EndDate],#1/1/2199#)));
Operators cannot be dynamic in a query object. Cannot be selected via a conditional expression. However, parameters can be dynamic. Suggest you construct a field with an expression that handles the nulls to return either of 2 values:
IIf([IDNumber] Is Null, "XXXX", "AAAA") AS Grp
Then to select either the Null or not Null records, apply conditional parameter to that field:
Grp = IIf([Forms]![MassCommunicationTool]![IncludeApplied]=0, "XXXX", "AAAA")
I've never used dynamic parameterized queries. I prefer VBA to construct filter criteria and apply to form or report.
I want to convert an SQL query into a JSONiq Query, is there already an implementation for this, if not, what do I need to know to be able to create a program that can do this ?
I am not aware of an implementation, however, it is technically feasible and straightforward. JSONiq has 90% of its DNA coming from XQuery, which itself was partly designed by people involved in SQL as well.
From a data model perspective, a table is mapped to a collection and each row of the table is mapped to a flat JSON object, i.e., all fields are atomic values, like so:
{
"Name" : "Turing",
"First" : "Alan",
"Job" : "Inventor"
}
Then, the mapping is done by converting SELECT-FROM-WHERE queries to FLWOR expressions, which provide a superset of SQL's functionality.
For example:
SELECT Name, First
FROM people
WHERE Job = "Inventor"
Can be mapped to:
for $person in collection("people")
where $person.job eq "Inventor"
return project($person, ("Name", "First"))
More complicated queries can also be mapped quite straight-forwardly:
SELECT Name, COUNT(*)
FROM people
WHERE Job = "Inventor"
GROUP BY Name
HAVING COUNT(*) >= 2
to:
for $person in collection("people")
where $person.job eq "Inventor"
group by $name := $person.name
where count($person) ge 2
return {
name: $name,
count: count($person)
}
Actually, if for had been called from and return had been called select, and if these keywords were written uppercase, the syntax of JSONiq would be very similar to that of SQL: it's only cosmetics.
I have a payment_request model and a payment_detail model. In the payment_request index I need to be able to search by first and last name which are stored in the payment_details table. I am newish to writing SQL and could use some help. I have what I believe to be the correct query below, but am not sure how to write that in my Rails controller so I can search by name.
SELECT first_name, last_name
FROM payment_details
LEFT OUTER JOIN payment_requests
ON payment_requests.id = payment_details.payment_request_id;
If you're using ActiveRecord models, you can skip all that and build that query with the ActiveRecord Querying Interface.
#payment_requests = PaymentRequest.joins(:payment_detail).where(payment_detail: {first_name: params[:first_name], last_name: params[:last_name]})
If you intent to show payment_details data on that index page, you should consider including that information in that query, so you avoid n+1 queries.
#payment_requests = PaymentRequest.includes(:payment_detail).where(payment_detail: { first_name: params[:first_name], last_name: params[:last_name]})
Note: You've got to have a complete match to use the above, so it may not be what you want.
I'd also recommend you use the Ransack gem to build complex queries. It would go something like this:
PaymentRequest.ransack(params[:q])
and in your views:
<%= f.search_field :payment_detail_first_name_or_payment_detail_last_name_cont %>
That would allow you to use just one field to query both columns.
You can do the following:
term_to_find = params[:search]
columns_to_search = %w( payment_details.first_name payment_details.last_name )
sql_conditions = []
columns_to_search.map |column_name|
sql_conditions.push("#{column_name} ILIKE :term_to_find")
end
PaymentRequest.includes(:payment_details)
.where(sql_conditions.join(' OR '), term_to_find: "%#{term_to_find}%")
This will find results containing the string you searched. Example: you typed "bob" in the search, it could find "bobby" or even "Mr. Bob" (the ILIKE makes the search case-insensitive)
I am using Postgres 9.3.2 to make a database of contacts.
Example: If i have a row in my table that looks something like this.
{
firstName : "First name"
lastName : "Last name"
emails : ["email#one.com", "email#two.com", "email#three.com]
}
PS: firstName, lastName and emails are columns in my db and the value associated is the value for that column for that specific row.
I want to be able to query the db so that if i query for the email "email#four.com" the result is nothing but if i query for "email#two.com" the result will be the above row entry.
I dont think the query
"Select * from contactTable where emails="email#two.com""
will work. instead i want to do something like
"Select * from contactTable where emails contains "email#two.com""
any ideas on how to do this?
"Select * from contactTable where emails contains "email#two.com""
I think you want:
"Select * from contactTable where thejsonfield -> emails
Example setup, after fixing up your totally broken json:
CREATE TABLE contacts AS SELECT '{
"firstName" : "First name",
"lastName" : "Last name",
"emails" : ["email#one.com", "email#two.com", "email#three.com"]
}'::json AS myjsonfield;
The following will work in PostgreSQL 9.4, but unfortunately does not in 9.3 due to the oversight of the missing json_array_elements_text function:
select *
from contacts,
lateral json_array_elements_text(myjsonfield -> 'emails') email
where email = 'email#two.com';
For 9.3, you have to use a clumsier method to scan the json array for matching values:
select *
from contacts,
lateral json_array_length(myjsonfield -> 'emails') numemails,
lateral generate_series(0, numemails) n
WHERE json_array_element_text(myjsonfield -> 'emails', n) = 'email#two.com';
You can't use the simple IN or = ANY constructs because (at this point) PostgreSQL doesn't understand that you might have a json array, so it'll fail with:
regress=> SELECT * FROM contacts WHERE 'email#two.com' = ANY (myjsonfield->'emails');
ERROR: op ANY/ALL (array) requires array on right side
LINE 1: SELECT * FROM contacts WHERE 'email#two.com' = ANY (myjsonfi...
^
as it expects a PostgreSQL array, not a json array, and there's no convenient builtin to turn a json array into a PostgreSQL array yet.
Postgres has support for parsing JSON. Here is documentation: http://www.postgresql.org/docs/9.3/static/functions-json.html. I can't give you more detailed answer since you didn't provide exact data and schema, but it's easy to find the right function in documentation.