我有两个表问题和答案,我想显示所有问题及其答案的详细信息。例如。 23(意见)12(答案)

时间:2010-12-02 12:38:52

标签: php mysql

如果没有答案,这不显示问题

SELECT 
  M.id, M.j_surname, 
  Q.id as qid, Q.qus_view_count, Q.qus_owner, Q.qus_title, Q.qus_description,
  Q.qus_createddate, 
  COUNT(A.qus_id) as ans_count, 
  A.qus_id FROM jt_questions Q 
LEFT JOIN jt_members M ON M.id = Q.qus_owner 
LEFT JOIN jt_answers A ON Q.id = A.qus_id 
GROUP BY A.qus_id 
ORDER BY Q.qus_createddate DESC 
LIMIT $offset, $recordsPerPage;

2 个答案:

答案 0 :(得分:2)

尝试GROUP BY Q.id而非GROUP BY A.qus_id

对于未回答的问题,A.qus_id的值均为NULL

答案 1 :(得分:0)

$ offset =“1; drop table jt_answers; - ”;

修改

如果您在代码中执行的操作如下所示:

$SQL = "SELECT 
  M.id, M.j_surname, 
  Q.id as qid, Q.qus_view_count, Q.qus_owner, Q.qus_title, Q.qus_description,
  Q.qus_createddate, 
  COUNT(A.qus_id) as ans_count, 
  A.qus_id FROM jt_questions Q 
LEFT JOIN jt_members M ON M.id = Q.qus_owner 
LEFT JOIN jt_answers A ON Q.id = A.qus_id 
GROUP BY A.qus_id 
ORDER BY Q.qus_createddate DESC 
LIMIT $offset, $recordsPerPage;";

我需要做的就是让$ offset看起来像我上面的原始答案。这会丢掉你的jt_answers表。

您可以验证这些值,例如确保$ offset是正整数。

但实际上你应该使用MySQLi的参数绑定。那将用?替换变量?并允许您将变量传递给它,以便数据库可以决定如何处理它们。

http://www.php.net/manual/en/mysqli-stmt.bind-param.php