使用sprintf进行ORDER,LIMIT和查询

时间:2012-05-01 22:14:22

标签: php mysql

我在向SQL查询中包含ORDER和LIMIT时遇到问题。

$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等。我有答案

  

致命错误:在“while(($ row_5_2 ...”

中的非对象上调用成员函数fetch_assoc()

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:1)

查看您的代码,您可能会收到以下错误(但请检查以确定):

Incorrect usage of UNION and ORDER BY

如果是这样,那是因为你没有括号。请参阅UNION的手册:

  

要将ORDER BY或LIMIT应用于单个SELECT,请将该子句放在括起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);