我们如何在MySql查询中的两个单独的字段中分配ORDER BY?

时间:2013-05-13 07:34:46

标签: mysql sql

我如何为mysql中的两个单独字段设置顺序

CODE

$sql = 'SELECT q.question_id, a.answer_id, q.question_name, a.option_name, q.display_order AS ques_order, a.correct, a.display_order AS opt_order FROM questions q JOIN answers a ON (a.question_id = q.question_id) WHERE test_id = '.$m_test_id.' ORDER BY ques_order, opt_order ASC'; 

错误消息:

  

MysqlError:你的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第4行的“ORDER BY ques_order,opt_order ASC”附近使用正确的语法

ORDER BY ques_­order,­ opt_­order ASC;

1 个答案:

答案 0 :(得分:4)

$m_test_id出了问题;它可能是空的并导致SQL语法问题。考虑使用准备好的陈述:

$sql = 'SELECT q.question_id, a.answer_id, q.question_name, a.option_name, q.display_order AS 
    ques_order, a.correct, a.display_order AS opt_order 
    FROM questions q 
    JOIN answers a ON a.question_id = q.question_id 
    WHERE test_id = :test
    ORDER BY ques_order, opt_order ASC'; 

$stmt = $db->prepare($sql);
$stmt->execute(array(':test' => $m_test_id));

除此之外,您应该首先找出$m_test_id为空的原因。

如果您没有使用PDOmysqli,则可以使用mysql_real_escape_string(),但请注意,它已被弃用,不应再使用。