I want to write mysql query to display all records if text field value = "All" or else display records similar to keyword value. I have written code below to just to give an idea.
if (keyword = 'All' )
select * from ItemMain
else if (keyword like %itemname%)
select * from ItemMain
Ok, assuming PHP as the front-end language you can put it all in one query like this (forgive the curly braces; I'm never sure when they're needed or not so I tend to over-use them):
$query = <<< ENDSQL
SELECT *
FROM ItemMain
WHERE ('{$keyword}' = 'All') OR (your_textfield like '%{$keyword}%')
ENDSQL;
... execute the query
But really I'd go with the suggestion from #cjg and use two different queries:
$query = "";
if ($keyword == 'All') {
$query = "SELECT * FROM ItemMain";
} else {
$query = "SELECT * FROM ItemMain WHERE your_textfield LIKE '%{$keyword}%'";
}
... execute the query
If itemname is your column name, and your search string parameter replaces the ? in your code. Then your statement should look something like this if you are searching for all itemnames containing your search string:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname LIKE '%?%'
Or this if you are looking for an exact match:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname = ?
Related
I want to find a way to use one query where I am replacing the LineUps.DIG output when it = Y. I'm wanting to mark as an asterisk in html. maybe it's better to do this on the front end vs sql query.
Fist query works and returns the data
$stmt = $conn->prepare("SELECT distinct Channel_LineUps.channel, Channel_LineUps.description, Channel_LineUps.Tier, LineUps.HD, LineUps.DIG FROM Channel_LineUps, LineUps WHERE (LineUps.Market_ID = Channel_LineUps.Market_ID AND Channel_LineUps.Market_ID = 28) ORDER BY Channel_LineUps.Tier ASC");
Second query is where i have the replace but am not sure how to merge with above query.
SELECT DIG,REPLACE(DIG,"Y","*") as output FROM LineUps WHERE DIG="Y");
I think CASE WHEN is what you are looking for:
$sql = <<<SQL
SELECT DISTINCT Channel_LineUps.channel, Channel_LineUps.description,
Channel_LineUps.Tier, LineUps.HD,
CASE LineUps.DIG WHEN "Y" THEN REPLACE(LineUps.DIG, "Y", "*") ELSE LineUps.DIG END
FROM Channel_LineUps, LineUps
WHERE (LineUps.Market_ID = Channel_LineUps.Market_ID
AND Channel_LineUps.Market_ID = 28)
ORDER BY Channel_LineUps.Tier ASC
SQL;
$stmt = $conn->prepare($sql);
You can also directly replace line 4 above with:
CASE LineUps.DIG WHEN "Y" THEN "*" ELSE LineUps.DIG END
as you know its value for sure.
I have an array of value :
words = ['foo', 'bar', 'baz']
I want autogenerate a where clause with LIKE (and not "IN").
What I do for now :
words = params[:content].split(' ').map { |w| "%#{w.strip}%" }
where = []
words.size.times do
where << 'name LIKE ?'
end
tags = Tag.where(where.join(' OR '), *words)
the correct request SQL is generate :
SELECT `tags`.* FROM `tags` WHERE (name LIKE '%foo%' OR name LIKE '%bar%' OR name LIKE '%baz%')
but it's not realy nice way...
when I want compare array values with equals, we can just do :
Tag.where(name: words)
There is a possibility to do same thing but not generate IN, but multiple OR LIKE "%VALUE%" ? How?
In postgresql it works like this:
Tag.where("name iLIKE ANY ( array[?] )", words)
SQL RLIKE (REGEX)
Tag.where("name RLIKE ?", words.join("|"))
SQL select (not very efficient):
Tag.select{ |c| c.name =~ Regexp.new(words.join("|"), true) }
As a scope in Tag.rb (SQL)
scope :ilike_any, -> (words) { where("name RLIKE ?", words.join("|")) }
That enables you to do:
words = %w(word1 word2 word3)
Tag.ilike_any(words)
I have a function which takes an argument that is used in where clause
function(string x)-->Now this will create a sql query which gives
select colname from tablename where columnname=x;
Now I want this function to give all rows i.e. query equivalent to
select colname from tablename;
when I pass x="All".
I want to create a generic query that when I pass "All" then it should return me all the rows else filter my result.
Just leave the where condition out.
If you really want it that complicated use
where columnname LIKE '%'
which will only filter nulls.
select colname from tablename
where columnname=(case when #x ="All" then columnname
else #x end)
Try this
select colname from tablename where 1=1
hope the above will work
where 1=1 worked for me, Although where clause was being used all records were selected.
You can also try
[any_column_name]=[column_name_in_LHL]
(LHL=left hand side.)
refer my answer for more details
I had the same issue some time ago and this solution worked for me
select colname from tablename where columnname=x or x = 'ALL'
SELECT * FROM table_name WHERE 1;
SELECT * FROM table_name WHERE 2;
SELECT * FROM table_name WHERE 1 = 1;
SELECT * FROM table_name WHERE true;
Any of the above query will return all records from table.
In Node.js where I had to pass conditions as parameter I used it like this.
const queryoptions = req.query.id!=null?{id : req.query.id } : true;
let query = 'SELECT * FROM table_name WHERE ?';
db.query(query,queryoptions,(err,result)=>{
res.send(result);
}
It's unclear what language you're using for your function, but you have to somehow parse the 'All' prior to getting to sql:
public void query(String param) {
String value = "":
switch (param) {
case 'All':
value = "*";
break;
default:
value = param;
}
String sql = "select colname from tablename where colname="+value;
//make the query
}
If you have to allow 'ALL' to be passed through as the parameter value to your function, then you will need to put some manipulation code in your function to construct your SELECT statement accordingly. I.e. You can detect if the parameter has 'ALL' in it and then omit the WHERE clause from your SQL statement. If a value other than 'ALL' comes through, then you can include the WHERE clause along with the relevant filter value from the parameter.
An example of a piece of code to do this would be;
IF x = 'ALL'
THEN
SELECT COLNAME FROM TABLENAME;
ELSE
SELECT COLNAME FROM TABLENAME WHERE COLUMNNAME = X;
END IF;
Give a conditional check in your code(assuming Java) to append the WHERE clause only when x != 'All'
mySqlQuery = "SELECT colname FROM tablename" +
(x.equals("All") ? "" : "WHERE columnname = "+x);
I have a string of IDs separated with comma
$myIDs = 22,23,45,895;
How do I write a query to return records for values that correspond to the IDs in my string?
This does not seem to be right:
SELECT *
FROM t1
WHERE itemID IN ($myIDs)
I guess I'm trying PHP array function here, hah? Is there something like this in mySQL?
Appreciate any suggestions. Thanks.
I think you're missing quotes, ie, the exact query should look like this before evaluation
SELECT *
FROM t1
WHERE itemID IN ('22','23','45','895');
Hence all you've got to do to fix this is:-
$myIDs = array(22,23,45,895);
$myIDs_string = "'".implode("','",$myIDs)."'";
then in whatever PHP/SQL library/framework you select, use PHP to execute the following php query:-
SELECT *
FROM t1
WHERE itemID IN ($myIDs_string);
Hope this helps.
$IDs = array(1,2,3,4,5);
// alternatively, you can write it like this...
// $IDs = "1,2,3,4,5";
if(is_array($IDs))
$IDs = implode(",",$IDs);
$query = "SELECT * FROM t1 WHERE itemID IN ($IDs)";
echo $query;
I just want somthing like this:
select SUM(*) from `mytable` group by `year`
any suggestion?
(I am using Zend Framework; if you have a suggestion using ZF rather than pure query would be great!)
Update: I have a mass of columns in table and i do not want to write their name down one by one.
No Idea??
SELECT SUM(column1) + SUM(column2) + SUM(columnN)
FROM mytable
GROUP BY year
Using the Zend Framework's Zend_Db_Select, your query might look like
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from('mytable', array('sum1' => 'SUM(`col1`)', 'sum2' => 'SUM(col2)')
->group('year');
$stmt = $select->query();
$result = $stmt->fetchAll();
Refer to the Zend_Db_Select documentation in the ZF manual for more.
EDIT: My bad, I think I misunderstood your question. The query above will return each colum summed, but not the sum of all of the columns. Rewriting Maxem's query so that you can use it with a Zend Framework DB adapter, it might look like
$sql = '<insert Maxem's query here>';
$result = $db->fetchAll($sql);
You might choose to use fetchCol() to retrieve the single result.
It sounds like you don't want to explicitly enumerate the columnn and that you want to sum all the columns (probably excluding the year column) over all the rows, with grouping by year.
Note that the method Zend_Db_Table::info(Zend_Db_Table_Abstract::COLS) will return an array containing the columns names for the underlying table. You could build your query using that array, something like the following:
Zend_Db_Table::setDefaultAdapter($db);
$table = new Zend_Db_Table('mytable');
$fields = $table->info(Zend_Db_Table_Abstract::COLS);
unset($fields['year']);
$select = $table->select();
$cols = array();
foreach ($fields as $field){
$cols[] = sprintf('SUM(%s)', $field);
}
$select->cols(implode(' + ', $cols));
$select->group('year');
I have not tested the specific syntax, but the core of the idea is the call to info() to get the fields dynamically.
Done in ZF rather than pure query and you don't have to write the name of the columns one by one.
(I assume you are extending Zend_Db_Table_Abstract)
If you're asking how to write
select SUM(*) from `mytable` group by `year`
This is how it is done:
public function sumOfAllFields(){
return $this->fetchAll( $this->select()->from('mytable','SUM(*)')->group('year') )->toArray();
}
Or not using Zend...
function mysql_cols($table){
$sql="SHOW COLUMNS FROM `".$table."`";
$res=mysql_query($sql);
$cols=array();
while($row=mysql_fetch_assoc($res))$cols[]=$row['Field'];
return $cols;
}
$cols=mysql_cols("mytable");
$select_sql=array();
foreach($cols as $col){
$select_sql[]="SUM(`".$col."`)";
}
$select_sql=implode('+',$select_sql);
$sql="select (".$select_sql.") from `mytable` group by `year`";