Search query to fetch data - mysql

I want write search query which fetch the data from students table based on multiple conditions like by ID , by name and by date of birth like that.
if I use OR condition like
Select * from students where Id='101' or name='Kumar' or age='21';
it will return if any one field is entered. If multiple fields are entered it will consider first only.
If I use AND condition like
Select * from students where Id='101' and name='Kumar' and age='21';
It will return only if all fields are entered. If any one of the field is empty it will return zero, I mean it will return empty. I want to get result even some fields are empty.
I'm using this quarry for swing application if I haven't enter text in one of the field then it will become empty like I'd='' not null
How to get Result at this condition
Select * from students where Id='' and name='' and age='21'

I want to get result even some fields are empty.
Then include that in your conditions. Something like this:
WHERE
(Id = '101' OR Id IS NULL) AND
(name = 'Kumar' OR name IS NULL) AND
(age = '21' OR age IS NULL)
Nesting conditions in parentheses allows you to build fairly complex conditional logic. How you define that logic for finding the records you want to find is really up to you.

Use LIKE clause without %s. So it'll be acting as a simple =. Here's how it will work.
if(txtId.getText().equals("")){
String id = "%%";
}else{
String id = txtId.getText();
}
if(txtName.getText().equals("")){
String name = "%%";
}else{
String name = txtName.getText();
}
if(txtAge.getText().equals("")){
String age = "%%";
}else{
String age = txtAge.getText();
}
resultset = statement.executeQuery("SELECT * FROM student WHERE id LIKE '"+ id +"' and name LIKE '"+ name +"' and age LIKE '"+ age +"';");
Try this out. It'll work like a charm. (It's up to you to change the query according to your database)

Related

Blank input Parameters in a WHERE condition of a SELECT statement

I have a report with 10 input parameters wherein only two are obligatory, the rest are optional. The problem is, as far as I know, if you use an input parameter that is blank in a WHERE condition of a SELECT statement no records will be selected from a table, so how to fix that ?
lets try something simple:
SELECT * FROM contrat WHERE article = 'sumsung' AND price = null
the user entered an article and did not enter a price
so the query will return nothing because price is null even when we have a contract with a sumsung article
If by blank you mean null or an empty string, you must construct for each of the optional parameters a condition like:
column_name = :optional_param OR :optional_param IS NULL
or:
column_name = :optional_param OR :optional_param = ''
So, your WHERE clause should look like:
WHERE <conditions for the non null parameters>
AND (column_name1 = :optional_param1 OR :optional_param1 IS NULL)
AND (column_name2 = :optional_param2 OR :optional_param2 IS NULL)
AND .......

How to make where condition always be true with field =?

I have a sql statement follow:
select * from table where id = ?
Now, problem is, l don't know whether front end will send me the value of id, if it did, this sql seem like id = 1, and if not, sql should be like id = true(fake code) to find all data
How could I write my sql?
Or, It is fundamentally wrong?
This is normally handled by using logic such as this:
select *
from table
where id = ? or ? is null;
If you don't want to pass the parameter twice or use named parameters:
select t.*
from table t cross join
(select ? as param) params
where id = params.param or params.param is null;
If you want to return all ids if the passed-in value does not exist:
select t.*
from table t
where id = ? or
not exists (select 1 from table t2 where t2.id = ?);
What you can try doing is in your code, write a function for fetching a specific record, and another function for fetching all the records from your table.
In PHP, it could be something like:
// Fetching a specific record
function getCustomerRecord($customerId) {
// Code to fetch specific record from database
}
// Fetching all records
function getAllCustomerRecords() {
// Code to fetch all records from database
}
In the function where you process requests received, check first if a value for id was passed. If a value for id was passed, call the function to fetch a specific record, making sure to pass along the value you received as an argument. Otherwise, call the function to fetch all the records from your table.
You can try doing this to get your right sql statement in PHP
function GetSqlStatement($id){
return $sql = "select * from table where id = ".$id.";";
}

MySQL where if statement

I'm currently working on an API using node.js and node-mysql.
I start off by grabbing all the parameters that the client sends over like this:
var userId = req.query.userId;
var carType = req.query.carType;
var hasOwnership = req.query.hasOwnership; (optional parameter)
What I would like to do is make a statement so that if the client sends the hasOwnership parameter with the request, my statement will return all the cars that belong to him with the specific car type. Similar to this:
SELECT * FROM cars WHERE car_type=? AND owner_id=?, [carType, userId];
Otherwise it will just return the all the cars that match the car type:
SELECT * FROM cars WHERE car_type=?, [carType];
Is it possible to accomplish something like this in a single query?
Thanks in advance!
You can phrase the query as something like this:
SELECT *
FROM car
WHERE (? is null or car_type = ?) AND
(? is null or owner_id = ?);
Note that this version takes each parameter twice, unless you use named parameters.
A dirty quick solution would be to use an if then else.
if hasOwnership has value the use query #1 else use query #2

How can I select data from mySQL table from rows that are not empty?

I want to select data from my table people (MySQL) but only where friend is not empty:
$sql = "SELECT * FROM people WHERE friend = '$friend' ORDER BY id ASC AND WHERE friend IS NOT NULL;" ;
I tried to write it like this, but it is not working. In this case it is selecting nothing.
Your SQL was malformed:
$sql = "SELECT * FROM people
WHERE friend = '$friend' AND friend != ''
AND friend IS NOT NULL
ORDER BY id ASC";
With that said it sounds like you don't want to query at all when $friend has no value:
if ($friend) {
$sql =... etc.
} else {
// No query, $friend had no value
}
You really want to insure your DB is as clean as possible (assuming you can at this point, and insure that you aren't inserting empty strings.
SELECT * FROM people WHERE friend!='' ORDER BY id ASC

Mysql like search with more than one column

I have a drupal site with the search option. If user enters the search keyword, i need to compare that with more than one columns and display the records.
I have tried the following query
$search = 'test';
$sql_query = db_select('logoinfo', 'l')->fields('l');
$or = db_or();
$or->condition('search_field', '%'.db_like($search).'%','LIKE');
$or->condition('companyname', '%'.db_like($search).'%','LIKE');
$sql_query->condition($or);
$selectlogos = $sql_query->execute();
It displays all the records matching the search keyword with the order of auto increment Id asc.
But i want to display the records first which is having both search_field and companyname matches with the keyword, after that other records which is matches with either companyname or search_field. Please advise to achieve this.
Since orderBy requires a field name and can't order by an expression, you'll need to use addExpression to get an alias and then order by that alias. The expression in my example will return 0 if the value is not in both fields and 1 if it is in both fields. As far as I know this should be standard SQL, but it may vary on different database backends; so the expression may need to be adjusted depending on the database you are using.
<?php
$search = 'test';
$sql_query = db_select('logoinfo', 'l')->fields('l');
$or = db_or();
$or->condition('search_field', '%'.db_like($search).'%','LIKE');
$or->condition('companyname', '%'.db_like($search).'%','LIKE');
$sql_query->condition($or);
$safe_search = db_like($search);
$ex_alias = $sql_query->addExpression("l.search_field LIKE '%$safe_search%' AND l.companyname LIKE '%$safe_search%'");
$sql_query->orderBy($ex_alias, 'DESC');
$selectlogos = $sql_query->execute();
?>