My question is: How to get different values in one sql query? I am trying this:
SELECT
q.id,
q.question_title,
SUM(op.option_value) AS total_votes,
COUNT(op.option_value) AS number_votes,
tab.comments
FROM
questions_options AS op
INNER JOIN questions AS q
ON (q.id = op.q_id)
INNER JOIN
(SELECT
SUM(p.unseen) AS comments
FROM
questions_options AS p) tab
ON (q.id = tab.q_id)
WHERE op.option_value > 0
GROUP BY q.question_title
This query is working perfectly, If i remove the middle “INNER JOIN” (i.e shows me the id, question title, sum of total votes rating, and the number of votes….
But I want to show unseen comments also, which is another field in that table and takes “1” for unseen (unread) comment…
So how can I do this by putting unseen comments number….any idea or suggestions…
I think Judge Mental is right.
You should SELECT the “q_id” field in your subquery to be able to make an inner join to “tab.q_id”.
-Explanation-
Your first
INNER JOINlooks like this:SELECT * FROM questions_options AS op INNER JOIN questions AS q ON (q.id = op.q_id)..so basically the relation (and join) between your two tables is based on
questions.idandquestions_options.q_id.Well, it’s the same story for you subquery.
In your subquery you define a SELECT statement FROM “questions_options”,
which will only return the columns/fields you put after your SELECT.
(SELECT SUM(p.unseen) AS comments FROM questions_options AS p) tabTo be able to use any data from you subquery, you will have to
SELECTthequestions_options.q_idfield and make a join with thequestions.idfield alreadyin your main query.
(SELECT p.q_id, SUM(p.unseen) AS comments FROM questions_options AS p) tabINNER JOIN (...subquery...) ON (q.id = tab.q_id)
So
tab.q_idrefers to thep.q_idyou selected in your subquery.