Getting catagory title total number of questions and answers order by number of questions

dba.stackexchange https://dba.stackexchange.com/questions/280955

  •  11-03-2021
  •  | 
  •  

Question

I have three tables. Which is in at this fiddle, http://sqlfiddle.com/#!9/4cadb2

Which is like this?.

CREATE TABLE `user_answers` (
  `id` int(250) NOT NULL,
  `question_id` varchar(250) NOT NULL,
  `user_id` int(250) NOT NULL,
  `answer` text NOT NULL,
  `date` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `user_questions` (
  `id` varchar(250) NOT NULL,
  `user_id` int(250) NOT NULL,
  `note_id` int(250) NOT NULL,
  `title` text NOT NULL,
  `question` text NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `material_univarcity_list` (
  `id` int(100) NOT NULL,
  `name` varchar(50) NOT NULL,
  `about` mediumtext NOT NULL,
  `date` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

I want to get a resultant table which has count - Name(Name is from material_univarcity_list) Total number of questions to that particular name. Here id of material_univarcity_list table is the note_id of user_questions and I want total number of answers to that particular catagory here question_id is the id of user_questions. How can I do this?

My expected result is like

no|catagory        |number_of_questions |number_of_answers
 1|DBMS 5th sem ISE|            2       | 3
 2|DBMS 6th sem ISE|            1       | 1

How can i do this?

Was it helpful?

Solution

SELECT @no := @no + 1 AS no
  ,catagory
  ,number_of_questions
  ,number_of_answers
FROM (
SELECT c.title AS catagory        
    ,COUNT(DISTINCT q.id) AS number_of_questions 
    ,COUNT(a.id) AS number_of_answers
FROM material_univarcity_list_content AS c
LEFT JOIN user_questions AS q ON q.note_id = c.id
LEFT JOIN user_answers AS a ON a.question_id = q.id
GROUP BY c.title ) AS t1
CROSS JOIN (SELECT @no := 0) AS t2
ORDER BY number_of_questions DESC;

Since you use MySQL 5.7 which doesn't support window functions like ROW_NUMBER you need to use user variables to emulate it.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top