嗨, friend 们,我正在列出 php 中的主题,这些主题可能与多个类别相关联
我的数据库架构是
topics
topic_id
user_id
topic_name
category
category_id
category_name
topic_category (for association)
tc_id
topic_id
category_id
topic_response//结果
tr_id
topic_id
response ( given in a form of 5 star rating so its in range of 1-5 always )
user_id
我需要做的是
1st ) 根据回复列出前十个主题,这将基于回复数量
我试过了 ->
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
不工作
第二)用户将看到主题列表。他可以选择他想要的类别,也可以是多个。
例如
如果他选择category_id 1,2,3,4
,则将列出此类别中列出的主题。
我已经尝试过
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) 如果我得到一个查询工作假设。
从 php 端,我将从选择多个下拉列表中获取一个category_id 数组 就像数组(1,2,3,4)
所以我在想如何让这个查询接受类别ID
在mysql查询中以category_id IN (1,3,2,4)
的形式**
**我可以直接传递一个数组吗
category_id IN ($ids)
其中 $ids
是一个数组**
我是mysql新手,请帮助我 我们将不胜感激您的帮助:)
最佳答案
对于第一个问题:
您必须使用 LEFT JOIN 并将(响应的主题 id 行)与(主题 id)匹配,然后对(响应的主题 id)进行计数并按(响应的主题 id)对所有内容进行分组。
例如:
响应表 = 响应
response_id
主题_id
响应消息
主题表=主题
ID
标题
内容
查询是
从主题中选择主题.标题、主题.内容、COUNT(responses.topic_id) AS 计数 LEFT JOIN 响应 ON topic.id =response.topic_id GROUP BY 计数 LIMIT 10
对于问题 2:
- 您可以尝试使用 AND ( IN 1 OR 2 OR 3 OR 4
- 您可以尝试使用 BETWEEN 1 AND 4
- 哪里(category_id>=1&&category_id<=4)
关于php - 从多个类别获取主题并显示前十个主题以及 mysql/php 中的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11661352/