2014-03-27 116 views
0

我再次卡在MySQL查詢,我想一些幫助。與where子句和if語句的MySQL查詢

我試圖找到最好的方法來做到這一點。我想要做的是檢查$ var ='x'並基於它運行不同的查詢。代碼的

部分:

if ($var1 == '0' AND $var2 != '0' AND $var3 != '0' AND $var4 != '0') { 
    echo $query = "SELECT * FROM table WHERE var1 = ''"; 
}elseif ($var1 == '1' AND $var2 != '0' AND $var3 != '0' AND $var4 != '0') { 
    echo $query = "SELECT * FROM table WHERE var1 = '1'"; 
}elseif ($var1 != '0' AND $var2 == '0' AND $var3 != '0' AND $var4 != '0') { 
    echo $query = "SELECT * FROM table WHERE var2 = ''"; 
}elseif ($var1 == '0' AND $var2 == '0' AND $var3 != '0' AND $var4 != '0') { 
    echo $query = "SELECT * FROM table WHERE var1 = '' AND var2 = ''"; 
} etc.. 

的連接有很多。有一個更好的方法嗎?幾乎每個變量(共7個)有3個不同的選擇。我不能把var = $var WHERE子句下,因爲有時當我$var = '0'意味着所有的結果,所以我甚至不把它放在那裏..

這是方式的過濾腳本/代碼..

這對你有意義嗎? 謝謝!

+0

如果例如'$ var1 == 0'和'$ var2 == 0'發生了什麼......每個單一組合都有if語句嗎?如果不是的話,你可以用||(OR) – superphonic

+0

來限制它的幾個語句.-「有一個if語句,對於每一個單一的組合,的確很多.. – user3465843

回答

2

我認爲這可以用單個查詢和不同的WHERE條件來完成。您需要先定義何時在您的WHERE子句中放入var1 = ''。你應該在你的查詢中逐一找到需要varX = ''的情況。

$conds = array(); 
if ($var1 == '0' || $var2 == '0') { 
    $conds[] = "var1 = ''"; // this should be the only point where var1 is included in your query, so you need to have every possible condition in this if part 
} 
if ($var3 == '0' && $var4 != '0') { 
    $conds[] = "var3 = ''"; 
} 
// ..etc.. 
$query = "SELECT * FROM TABLE WHERE " . implode(' AND ', $conds); 
+0

像一個魅力一樣工作!Tyvm! – user3465843

0

如何:

$where_parts = array(); 
if (isset($var1)) { 
    if ($var1 == 0) { $var1 = ''; } 
    $where_parts [] = "var1 = '" . $var1 . "'"; 
} 
if (isset($var2)) { 
if ($var2 == 0) { $var2 = ''; } 
    $where_parts [] = "var2 = '" . $var2 . "'"; 
} 
if (isset($var3)) { 
if ($var3 == 0) { $var3 = ''; } 
    $where_parts [] = "var3 = '" . $var3 . "'"; 
} 
if (isset($var4)) { 
if ($var4 == 0) { $var4 = ''; } 
    $where_parts [] = "var4 = '" . $var4 . "'"; 
} 

$query = "SELECT * FROM table WHERE " . implode(' AND ', $where_parts); 
+0

幾乎與我選擇的答案一樣!Tyvm的幫助!(它似乎是完全一樣的東西,但你的方式有一些額外的行哈哈) – user3465843

0

是否有可能讓你只專注於變量是相關的查詢?例如:

$str = ""; 

# When will "var1" be in the query 
switch($var1) { 
    case '0' : $str .= " AND $var1=''"; break; 
    case '1' : $str .= " AND $var1='1'"; break; 
} 

# When will "var2" be in the query 
switch($var2) { 
    case '0' : $str .= " AND $var2=''"; break; 
    case '1' : $str .= " AND $var2='1'"; break; 
} 

... 

# If not empty then remove the first " AND " 
if(!empty($str)) { 
    $str = substr($str,4); 
} 

# Final query is a lot of concatenated strings 
$query = "SELECT * FROM table WHERE $str"; 

它可能不是代碼最優化的,但它很容易理解。

+0

謝謝你的幫助隊友,但它似乎有點複雜,比我其他答案 – user3465843