0

我在 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 ...”

任何人都可以帮忙吗?

4

1 回答 1

1

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

UNION 和 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);
于 2012-05-01T22:20:04.187 回答