9阅网

您现在的位置是:首页 > 知识 > 正文

知识

mysql - MySQL - 在GROUP BY之后加入更多条件的语法。

admin2022-11-04知识15

我有一个查询,其中列出了问题或博客,或两者。 问题有答案,博客没有。 它们在同一个表中,并且具有相同的结构(标题与细节),TYPE指定为 "博客 "或 "问题"。 答案表是POSTS,使用question_id作为两个表的共同字段。

用户界面允许用户在问题、博客、已回答、未回答上打勾,或者在问题文本本身输入搜索参数。

一个典型的类型条件是

$type_condition = " AND questions.type='question'";
$type_condition = " AND questions.type='blog'";

我的问题是在答题条件中。 我可以做到。

$answer_condition = 'HAVING answers = "0"';//questions with no answers    
$answer_condition = 'HAVING answers > "0"';//questions with answers
$answer_condition = 'HAVING answers > "-1"';//questions with and without answers

但我只想让$answer_condition适用于type="question "而忽略type="blog "的情况。 如果只有blog,或者只有question是复选框,这就不是问题。 但如果两者都被选中,就意味着用户想把两者都列出来,而answerercount条件应该只适用于type=question,而不是type=blog。

我想把这样的事情作为一个整体条件来做。

AND (questions.type='blog' OR (questions.type='question' AND answers ".$answer_condition."))";

但是,我知道这种语法在GROUP BY之后不会被接受, $answer_condition必须放在GROUP BY之后。 除了上面我概述的逻辑外,其他的查询都能用。

的SQL。

"SELECT questions.*, count(posts.question_id) as answers
FROM questions
LEFT JOIN posts
ON questions.question_id = posts.question_id  
WHERE question LIKE '%".$search."%'
".$type_condition."
GROUP BY questions.question_id
".$answer_condition."

countanswers字段=0的类型=blogs。

我如何通过SQL来实现?



【回答】:

这个问题可以通过将 "类型 "条件和 "答案 "条件都移到查询的HAVING子句来解决。 选项如下。

  • 问题 - questions.type='question'
  • 博客 - questions.type='blog'
  • 答复: (questions.type='question' AND answers > 0)
  • 无人问津- (questions.type='question' AND answers = 0)

如果用户选择了多个复选框,可以用 "OR "将它们互相追加。