I am creating a table of all the users listing their username and pending questions with total number of allotted question.
I have 2 tables first one contain the username,initial question number and final question number columns and second table contain the timestamp username and submitted question number
first db table
username | first que | last que |
---|---|---|
usera | 101 | 200 |
userb | 201 | 300 |
userc | 301 | 400 |
second db table
username | submitted question number | timestamp |
---|---|---|
usera | 103 | 13-06-2022 |
usera | 102 | 11-06-2022 |
userb | 201 | 12-06-2022 |
usera | 101 | 09-06-2022 |
so i want to output it as a username,total question allotted, pending question
Output i want on webpage
username | total question allotted | pending question |
---|---|---|
usera | 99 | 96 |
userb | 99 | 98 |
usera | 99 | 99 |
total pending question must be calculated as by (total questions in series - total submitted questions)
CodePudding user response:
You can done this using next query:
SELECT
first_table.username,
(last_que-first_que) total_questions_allotted,
(last_que-first_que-answers) pending_questions
FROM first_table
JOIN (
SELECT username, COUNT(*) answers FROM second_table GROUP BY username
) second_table_groupped USING(username);
or using next PHP code:
<?php
$query = 'SELECT
first_table.username,
(last_que-first_que) total_questions_allotted,
(last_que-first_que-answers) pending_questions
FROM first_table
JOIN (
SELECT username, COUNT(*) answers FROM second_table GROUP BY username
) second_table_groupped USING(username)';
$result = $mysqli->query($query);
$data = $result->fetch_all(MYSQLI_ASSOC);
print_r($data);