2012-05-01 67 views
0

我有包括ORDER和LIMIT到SQL查詢中的問題。ORDER,LIMIT和使用sprintf查詢

$STH_1 = $DBH_R->query("SELECT table_name       
         FROM information_schema.tables       
         WHERE table_name       
         LIKE 'v_c_ei\_9%' 
         "); 
$stmts_1 = array(); 

//echo "date = ".  $date."<br>";         // $date is today date 
$date_60 = date('Y-m-d', strtotime('-60 day', strtotime($date)));  // $date_60 = today - 60 days 


while (($row_1 = $STH_1 -> fetch_assoc()) !== null){ 

$table_name = $row_1['table_name']; 
$stmts_1[] = sprintf("SELECT * 
         FROM $table_name 
         WHERE (date_time >= '$date_60') AND (ei_code = '1117')  
        ");  
} 

// at this place I need help, I think. I have few data from every query but I want to reduce the number of solutions to 1 per table 

$stmt_1 = implode("\nUNION\n", $stmts_1); 
$stmt_1 .= "\nORDER BY date_time ASC";  
$STH_5_2 = $DBH_R->query($stmt_1);   
while (($row_5_2 = $STH_5_2 -> fetch_assoc()) !== null){ 

上面的腳本工作正常。但我想限制數據的數量(我只需要每個表中的最後一個)。我嘗試通過

ORDER BY date_time DESC LIMIT 0,1 

在sprintf查詢但它不想工作。當我添加ORDER等。我有答案

Fatal error: Call to a member function fetch_assoc() on a non-object in "while (($row_5_2 ..."

任何人都可以幫助嗎?

+1

當您通過sprintf查詢嘗試時,代碼的外觀如何?你檢查從MySQL錯誤? –

+0

@MarkByers可能沒有什麼,因爲他似乎使用mysqli。試試'echo $ DBH_R->錯誤;' –

回答

1

看你的代碼,這很可能是你很可能得到以下錯誤(但請對此予以肯定):

 
Incorrect usage of UNION and ORDER BY 

如果是這樣,那是因爲你缺少括號。請參閱UNION的手冊:

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) 
UNION 
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10); 
+0

這部分UNION和ORDER工作正常。我必須選擇接收數據BEFORE UNION,並且我嘗試按照我寫的(使用sprintf查詢中的ORDER)執行此操作,並且此ORDER不想工作... :( – Andrew

+0

答案相當簡單 - > ORDER BY never馬克 - 理論上你的解決方案是可以的,但不是在這個問題上 - 我們不知道我們有多少桌子 - 從第一個查詢來看這是必要的... – Andrew

+0

Mark,thinks for your help ... but I請記住您的評論你沒有刪除哪一個有時新來的醫生得到更好的... – Andrew