2015-10-19 84 views
0

我想從一個例子開始:你收到了一些帶有必要字段的列表。此列表可能會有所不同,即使它爲空,請選擇所有字段。該列表可以包含來自多個表格的字段。有沒有什麼辦法來產生這樣做的SELECT查詢?如何使用動態創建的查詢搜索數據庫?

可能有一種方法,但它看起來像解析收到的列表,添加適當的表別名,然後將修改後的列表添加到select子句中。實際上它是最好的方式嗎?

更新1

  • 的目標只是獲得通過從多個表中的字段,而不是從任何人(其關於第一個答案) 控制結果
+0

您需要根據您擁有的搜索信息動態構建查詢。很難提供沒有任何細節的正確答案,或者除非您可以將其縮小到特定問題。 –

+0

我只想問是否有比我更好的解決方案。目前沒有遇到任何其他問題 – Boog

+0

您不會告訴我們您的解決方案是什麼,以便我們可以告訴您替代方案。 – user1092289

回答

1

您可以創建根據您的標準,首先動態選擇字段的查詢。例如

假設您有兩個標準傳遞給您。然後(確保您的criteria1和criteria2安全後):

$mySelect = '';  //placeholder so that you can add select fields 
$extraTables = ''; //placeholder to put the extra tables I may need 
$criteria = " WHERE 1 "; //this will select everything 
if ($criteria1>'') { 
    $mySelect .= ' , t3.field3 '; 
    $extraTables = " , aDifferentTable AS t3"; 
    $criteria .= " AND t3.someKey = t1.someKey '"; 
    $criteria .= " AND field_crit1 = '" . $criteria1 . "'"; 
} 

//and an example of connecting dynamically to an other table 
if ($criteria2>'') { 
    $mySelect .= ' , t2.field5 '; 
    $extraTables = " , anOtherTable AS t2"; 
    $criteria .= " AND t2.someKey = t1.someKey '"; 
    $criteria .= " AND t2.field_crit2 = '" . $criteria2 . "'"; 
} 

//lets combine all together into one dynamically created query  
$myquery = "SELECT t1.something " . $mySelect . " FROM myTable AS t1"; 

$myquery = $myqury . $extraTables . $criteria;