简体   繁体   English

带计数条件的SQL选择

[英]sql select with count condition

I have 2 tables in my DB, first table called "questions" and hold questions with id, second table called "answers" and hold answers for the questions (as multiple choices). 我的数据库中有2个表,第一个表称为“问题”,并保存具有ID的问题,第二个表称为“答案”,并保留问题的答案(作为多项选择)。

how to select questions that have less than 4 answers? 如何选择答案少于4个的问题?

questions table: 问题表:

id     question
1      what is ...?
2      how many ...?
3      Is ....?

answers table 答案表

id     question_id     answer
1          1             54
2          1             11
3          1             22
4          2            England
5          1              5
6          2            Turkey

how to select questions that have answers less than 4? 如何选择答案小于4的问题?

thanks, 谢谢,

select questions.id, questions.question from questions 
inner join answers on questions.id = answers.question_id
group by questions.id, questions.question having count(questions.id) <4

here you go. 干得好。

use this : 用这个 :

SELECT * 
FROM questions 
WHERE id in
    (
    SELECT question_id 
    from answers 
    group by question_id 
    having count(question_id) <4
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM