Hi friends i am listing topics in php which may be associated with multiple category
my db schema is
topics
topic_id
user_id
topic_name
category
category_id
category_name
topic_category (for association)
tc_id
topic_id
category_id
topic_response // for results
tr_id
topic_id
response ( given in a form of 5 star rating so its in range of 1-5 always )
user_id
what i need to do is
1st ) list top ten topics based on responses ya it will be based on count of responses
i tried ->
select t.* ,count(tr.response) as votes from topics t , topic_response tr where t.topic_id=tr.topic_id group by tr.topic_id order by votes LIMIT 10
not working
2nd) user will be shown list of topic . he can choose the category in which he wants that can be multiple too.
for example
if he chooses category_id 1,2,3,4 then topics listed in this category will be listed.
i have tried to
select t.* from topics t ,topic_category tc where tc.topic_id = t.topic_id and category_id IN (1,3,2,4)
// not able to get idea on this i would prefer if i could do this in subquery since i also need to check if the user has already responded to that question .
**3) in case if i get a query working suppose .
from php side i will be getting an array of category_id from select multiple dropdown
like array(1,2,3,4)
so i was thinking how will make this query accept category id
in form of category_id IN (1,3,2,4) in mysql query**
**can i directly pass an array like
category_id IN ($ids) where $ids is an array**
i am a newbie in mysql please help me
you help will be appreciated 🙂
For the first question:
You have to use LEFT JOIN and match (response’s topic id row) to (topic’s id) then count(response’s topic id) and GROUP everything by (response’s topic id).
for example:
Responses Table = responses
response_id
topic_id
response_message
Topics Table = topics
id
title
content
The query is
SELECT topics.title,topics.content,COUNT(responses.topic_id) AS count FROM topics
LEFT JOIN responses ON topics.id = responses.topic_id GROUP BY count LIMIT 10
For question 2: