Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql - if value = 0 shorten where statement

Tags:

php

mysql

where

I wonder if it's possible to shorten query depending on some variable value in elegant way.

For example: I have value named $var = 0 and I would like to send a query that looks like this:

$query = "SELECT id, name, quantity FROM products WHERE quantity > 100";

But whan the $var != 1 I'd like to send a query like this:

$query = "SELECT id, name, quantity FROM products WHERE quantity > 100 AND id = '$var'";

So depending on value of $var I want to execute one of queries. They differ only with last expression. I found two possible solutions but they are not elegant and I dont like them at all.

One is made in php:

if ( $var == 0 ) {
  $query_without_second_expression
} else {
  $query_with_second_expression
}

Second is made in mysql:

SELECT WHEN '$var' <> 0 THEN id, name, quantity 
FROM products WHERE quantity > 100 AND id = '$var' ELSE id, name, quantity 
FROM products WHERE quantity > 100 END

but i dont like it - each idea doubles queries in some whay. Can I do something like this?

SELECT id, name, quantity 
FROM products WHERE quantity > 100 
CASE WHEN $var <> 0 THEN AND id = '$var' 

It's much shorter, and adds part of query if needed. Of course real query is much more complicated and shorter statement would be really expected. Anyone has an idea?

like image 712
Kalreg Avatar asked Apr 10 '12 14:04

Kalreg


People also ask

What is %s and %D in MySQL?

12 years, 11 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.

How do you show months if it has no record and force it to zero if NULL on MySQL?

You can append that into your query like: SELECT IFNULL(SUM(total),0) as total_orders, mnt from (SELECT MONTHNAME(created_at) mnt FROM orders GROUP BY MONTHNAME(created_at)) mn LEFT JOIN orders o ON mn.

Can we use if condition in MySQL query?

MySQL IF() FunctionThe IF() function returns a value if a condition is TRUE, or another value if a condition is FALSE.


2 Answers

If I understand well..

$query = "SELECT id, name, quantity FROM products WHERE quantity > 100";
if ( $var != 0 ) {
  $query .= " AND id = '$var'";
}

do you like it?

like image 89
Massimo Avatar answered Sep 21 '22 15:09

Massimo


You could so something like this on the SQL side:

"SELECT id, name, quantity FROM products WHERE quantity > 100 AND (id = '$var' OR '$var' = 0) 

But performance could be impacted. I would suggest building the appropriate query on the PHP side.

like image 30
ESG Avatar answered Sep 20 '22 15:09

ESG